Three ways to implement Ping in Java and how to differentiate Linux

Source: Internet
Author: User
Tags pings readline

The first half of the part turns from: 52317650

Check the operating status of the equipment, and some use ping to detect. Therefore, you need to use Java to implement the ping function.
In order to use Java to realize the function of Ping, it is recommended to use the Java Runtime.exec () method to directly invoke the ping command of the system, also someone completed the pure Java implementation of Ping program, using the Java NIO package (native IO, efficient IO Package )。 But device detection just wants to test if a remote host is available. Therefore, the following three ways can be implemented:

The Inetaddresss Way of 1.jdk1.5

ICMP Ping has been implemented since the Java 1.5,java.net package.
See: Ping Class (String) function.
It should be noted that if a remote server is set up with a firewall or related configuration, the results may be affected. In addition, the Isreachable method tries to connect to the remote host's TCP port 7 (Echo), because the program must have certain permissions on the system to send the ICMP request.

2. The simplest way to call CMD directly

See the PING02 (String) function of the Ping class.

3.Java calling the console to perform a ping command

The concrete idea is this:
The program calls a command like "Ping 127.0.0.1-n 10-w 4", which will ping 10 times, and if fluent will output a reply similar to "from 127.0.0.1: bytes =32 time <1ms ttl=64" The text (specific figures vary according to the actual situation), in which Chinese is localized according to the environment, some of the Chinese parts of the machine are in English, but the words "<1ms ttl=62" are always fixed at the back of the English language environment, which indicates that the result of a ping is able to pass. If the number of occurrences of this typeface equals 10 times the number of tests, then the 127.0.0.1 is fully capable of being connected.
Technically: The DOS command is specifically invoked with the Runtime.getruntime (). exec implementation to see if the string conforms to the format implemented with regular expressions.
See Ping class Ping (string,int,int) function.

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import java.net.InetAddress;
Import java.net.UnknownHostException;
Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;

public class Ping {

public static Boolean ping (String ipAddress) throws Exception {
int timeOut = 3000; The timeout should be above 3 banknotes
Boolean status = Inetaddress.getbyname (ipAddress). isreachable (TimeOut); When the return value is true, it indicates that host is available and false is not.
return status;
}

public static void Ping02 (String ipAddress) throws Exception {
String line = null;
try {
Process Pro = Runtime.getruntime (). EXEC ("ping" + ipAddress);
BufferedReader buf = new BufferedReader (New InputStreamReader (
Pro.getinputstream ()));
while (line = Buf.readline ()) = null)
System.out.println (line);
} catch (Exception ex) {
System.out.println (Ex.getmessage ());
}
}

public static Boolean ping (String ipAddress, int pingtimes, int timeOut) {
BufferedReader in = null;
Runtime r = Runtime.getruntime (); The ping command to be executed, which is a command in Windows format
String Pingcommand = "Ping" + ipAddress + "-n" + Pingtimes + "-w" + TimeOut;
try {//execute command and get output
System.out.println (Pingcommand);
Process p = r.exec (Pingcommand);
if (p = = null) {
return false;
}
in = new BufferedReader (New InputStreamReader (P.getinputstream ())); Check output row by line to calculate the number of occurrences similar to the =23ms ttl=62 typeface
int connectedcount = 0;
String line = null;
while (line = In.readline ()) = null) {
Connectedcount + = Getcheckresult (line);
}//If a typeface like =23ms ttl=62 appears, the number of occurrences = the number of tests returns True
return connectedcount = = Pingtimes;
} catch (Exception ex) {
Ex.printstacktrace (); Returns False if an exception occurs
return false;
} finally {
try {
In.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
If line contains =18ms ttl=16, it indicates that it is ping, returns 1, or returns 0.
private static int Getcheckresult (String line) {//System.out.println ("The result of the console output is:" +line);
Pattern pattern = Pattern.compile ("(\\d+ms) (\\s+) (ttl=\\d+)", pattern.case_insensitive);
Matcher Matcher = Pattern.matcher (line);
while (Matcher.find ()) {
return 1;
}
return 0;
}
public static void Main (string[] args) throws Exception {
String ipAddress = "127.0.0.1";
System.out.println (Ping (ipAddress));
PING02 (ipAddress);
System.out.println (Ping (ipAddress, 5, 5000));
}
}


Summary:
The first method: Jdk1.5 's inetaddresss, the code is simple. This method pings when a firewall is opened on the end machine, and the third method can ping.
The second approach: Use Java to invoke the cmd command, which is the simplest way to display the ping process locally.
The third method: Also use Java call Console ping command, this is more reliable, but also universal, easy to use: Incoming IP, set the number of pings and timeouts, you can determine whether to ping through the return value.

--In addition, when using the third method, it is important to distinguish the operating system

String osname = System.getproperty ("Os.name");//Get OS type
String Pingcommand = "";
if (Osname.tolowercase (). Contains ("Linux")) {
Pingcommand = "ping-c 3-i 0" +IP;
}else
Pingcommand = "Ping" +ip+ "-n 3-w 1000";

Three ways to implement Ping in Java and how to differentiate Linux

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.