How does java determine whether ping can pass a certain address

  • 2021-11-29 07:00:09
  • OfStack

Directory java can determine whether ping can pass a certain address java to achieve ping function 3 methods 1. Jdk1.5 InetAddresss mode 2. The simplest way, directly call CMD3.Java call console to execute ping command summary 1 it:

java judges whether ping can pass a certain address


/**
 * @description:  Determine whether it is possible ping Pass a certain address ,10s Inside ping5 Sub-average ping Tong 
 * @params: url Website or IP , such as: www.baidu.com   220.181.38.148
 * @return:
 * @auther: WZH
 * @date: 2020/1/29 21:49
 */
public static boolean canPing(String url) {
	return ping(url,5,10);
}
 
public static boolean ping(String ipAddress, int pingTimes, int timeOut) {
	BufferedReader in = null;
	Runtime r = Runtime.getRuntime();
	//  To be executed ping Command , This command is windows Format command 
	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;
		}
		//  Check the output line by line , Calculations appear similarly =23ms TTL=62 Number of words 
		in = new BufferedReader(new InputStreamReader(p.getInputStream()));
		int connectedCount = 0;
		String line;
		while ((line = in.readLine()) != null) {
			connectedCount += getCheckResult(line);
		}
		//  If something similar occurs =23ms TTL=62 Such words , Number of occurrences = The number of tests returns true 
		return connectedCount == pingTimes;
	} catch (Exception ex) {
		ex.printStackTrace();
		//  False is returned if an exception occurs 
		return false;
	} finally {
		try {
			assert in != null;
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
 
private final static Pattern PATTERN= Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)", Pattern.CASE_INSENSITIVE); 
private static int getCheckResult(String line) {
	// If line Contain =18ms TTL=16 Typeface , Indicates that the ping Tong , Return 1, If not, return 0.
	Matcher matcher = PATTERN.matcher(line);
	if (matcher.find()) {
		return 1;
	}
	return 0;
}

Three Methods for java to Realize ping Function

The running status of detection equipment is detected by ping. Therefore, java is needed to implement ping function.

In order to use java to realize the function of ping, some people recommend using Runtime. exec () method of java to directly call Ping command of the system, while others have completed the program of realizing Ping with pure Java, using ES38io package of Java (ES38io, efficient IO package). However, device detection only wants to test whether a remote host is available.

Therefore, it can be implemented in the following three ways:

1. InetAddresss mode of Jdk1.5

The functionality of ICMP ping has been implemented in the java. net package since Java 1.5.

See: ping (String) function of Ping class, String is ip without port number.

When using, be aware that if the remote server has a firewall or related configuration, the results may be affected. In addition, since sending an ICMP request requires the program to have a set of permissions on the system, when this permission cannot be met, the isReachable method will try to connect to the remote host's TCP port 7 (Echo).

2. The simplest way is to call CMD directly

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

3. Java calls the console to execute the ping command

The specific idea is as follows:

A command like "ping 127.0. 0.1-n 10-w 4" is called through the program. This command executes ping 10 times, and if it passes, it will output a reply like "Reply from 127.0. 0.1: bytes = 32 times < 1ms TTL=64 "text (the specific number will change according to the actual situation), in which Chinese is localized according to the environment, and the Chinese part on some machines is English, but whether it is Chinese or English environment, the following" < The word 1ms TTL=62 "is always fixed, which indicates that the result of one ping is communicable. If the number of occurrences of this word is equal to 10 times, that is, the number of tests, then 127.0. 0.1 is 100% communicable.

Technically: The specific call dos command is implemented with Runtime. getRuntime (). exec, and the regular expression is used 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 in the 3 Beyond banknotes         
        boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut);     //  When the return value is true When, explain host Is available, false You can't. 
        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();  //  To be executed ping Command , This command is windows Format command   
        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 , Calculations appear similarly =23ms TTL=62 Number of words   
            int connectedCount = 0;   
            String line = null;   
            while ((line = in.readLine()) != null) {    
                connectedCount += getCheckResult(line);   
            }   //  If something similar occurs =23ms TTL=62 Such words , Number of occurrences = The number of tests returns true   
            return connectedCount == pingTimes;  
        } catch (Exception ex) {   
            ex.printStackTrace();   //  False is returned if an exception occurs   
            return false;  
        } finally {   
            try {    
                in.close();   
            } catch (IOException e) {    
                e.printStackTrace();   
            }  
        }
    }
    // If line Contain =18ms TTL=16 Typeface , Indicates that the ping Tong , Return 1, If not, return 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 1:

The first method: InetAddresss of Jdk 1.5, the code is simple.

Method 2: Use java to invoke the cmd command, which is the simplest way to display the ping process locally.

The third method is to use java to call the ping command of the console, which is reliable, general and convenient to use: pass in ip, set the times and timeout of ping, and you can judge whether ping passes according to the return value.


Related articles: