Three ways to implement ping function in Java

http://www.blogjava.net/marchalex/archive/2015/03/08/423292.html

Three methods of implementing ping function in Java To
detect the running status of the device, some use ping to detect it. So you need to use java to implement the ping function.
In order to use java to implement the ping function, some people recommend using java's Runtime.exec() method to directly call the system's Ping command, and some people have completed the pure Java implementation of Ping program, using Java's NIO package (native io, Efficient IO package). But device detection just wants to test if a remote host is available. Therefore, you can use the following three ways to achieve:
1.Jdk1.5 InetAddresss way
Since Java 1.5, the java.net package has implemented the ICMP ping function.
See: the ping(String) function of the Ping class.
When using, it should be noted that if the remote server is set up with a firewall or related configuration, it may affect the results. In addition, because sending an ICMP request requires the program to have certain permissions on the system, when this permission cannot be satisfied, the isReachable method will try to connect to the remote host's TCP port 7 (Echo).
2. The easiest way is to directly call
the ping02(String) function of the Ping class by calling CMD.
3. Java calls the console to execute the ping command
The specific idea is as follows:
Call a command like "ping 127.0.0.1 -n 10 -w 4" through the program, this command will execute ping ten times, if it goes well, it will output something like "Reply from 127.0.0.1: bytes=32 time<1ms TTL= 64” text (the specific number will vary according to the actual situation), the Chinese is localized according to the environment, and the Chinese part on some machines is in English, but regardless of the Chinese and English environment, the following words “<1ms TTL=62” Always fixed, it indicates that the result of a ping is OK. If the number of times this word appears is equal to 10 times, that is, the number of tests, it means that 127.0.0.1 is 100% connectable.
Technically: The specific invocation of the dos command is implemented by Runtime.getRuntime().exec, and the regular expression is implemented to check whether the string conforms to the format.
See the ping(String, int, int) function of the Ping class.
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 more than 3 notes       
        boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut); // When the return value is true, it means that the 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 to be executed Command, this command is a command in windows format 
        String pingCommand = "ping " + ipAddress + " -n " ​​+ pingTimes + " -w " + timeOut; 
        try { // Execute the command and get the output 
            System.out.println(pingCommand);  
            Process p = r.exec(pingCommand);  
            if (p == null) {   
                return false;  
            }
            in = new BufferedReader(new InputStreamReader(p.getInputStream())); // Check the output line by line, count the number of occurrences of words like =23ms TTL=62 
            int connectedCount = 0;  
            String line = null;  
            while ((line = in .readLine()) != null) {   
                connectedCount += getCheckResult(line);  
            } // If something like =23ms TTL=62 appears, the number of occurrences = the number of tests, then return true 
            return connectedCount == pingTimes; 
        } catch (Exception ex) {  
            ex.printStackTrace(); // return false 
            return false; 
        } finally {  
            try {   
                in.close();  
            } catch (IOException e) {   
                e.printStackTrace();  
            } 
        }
    }
    //If the line contains =18ms TTL=16, it means that the ping has been completed and returns 1, otherwise returns 0.
    private static int getCheckResult(String line) { // System.out.println( "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));
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326794341&siteId=291194637