Detailed explanation of various methods to realize ping function in Android

  • 2021-11-24 02:57:23
  • OfStack

Use java to implement ping functionality. And write to the file. In order to use java to implement the functions of ping, it is recommended to use java Runtime.exec() Method to directly call the Ping command of the system, and some people have completed the program of realizing Ping with pure Java, using NIO package of Java (native io, 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

Since Java 1.5, java. net package ICMP ping Function of.

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). The code is as follows:


 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;
  }

2. The simplest way is to call CMD directly


public static void ping1(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());
    }
  }

3. Java calls the console to execute the ping command

The specific idea is as follows:
Calling something like " ping 127.0.0.1 -n 10 -w 4 This command executes ping 10 times and, if successful, outputs something like "Reply from 127.0. 0.1: bytes = 32 times < The text of 1ms TTL=64 "(the specific numbers 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 a Chinese-English environment, the following" < The word 1ms TTL = 62 "is always fixed, indicating that the result of one ping is communicable. If the number of times this word appears 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 used Runtime.getRuntime().exec Implementation, check whether the string conforms to the format and use regular expressions to realize it. The code is as follows:


public static boolean ping2(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, No to 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; 
  }

4. Implement ping at the beginning of program 1, accept ping after running, and write it into a file

The complete code is as follows:


import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Ping {
  private static final String TAG = "Ping";
  private static Runtime runtime;
  private static Process process;
  private static File pingFile;
 /**
   * Jdk1.5 Adj. InetAddresss, Simple code 
   * @param ipAddress
   * @throws Exception
   */
  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;
  }
  /**
   *  Use java Call cmd Command , This way is the simplest, you can put ping The procedure of is displayed locally. ping Out the corresponding format 
   * @param url
   * @throws Exception
   */
  public static void ping1(String url) throws Exception {
    String line = null;
    //  Get the host name 
    URL transUrl = null;
    String filePathName = "/sdcard/" + "/ping";
     File commonFilePath = new File(filePathName);
    if (!commonFilePath.exists()) {
      commonFilePath.mkdirs();
      Log.w(TAG, "create path: " + commonFilePath);
    }
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    String date = df.format(new Date());
    String file = "result" + date + ".txt";
    pingFile = new File(commonFilePath,file);
    try {
      transUrl = new URL(url);
      String hostName = transUrl.getHost();
      Log.e(TAG, "hostName: " + hostName);
      runtime = Runtime.getRuntime();
      process = runtime.exec("ping " + hostName);
      BufferedReader buf = new BufferedReader(new InputStreamReader(process.getInputStream()));
      int k = 0;
      while ((line = buf.readLine()) != null) {
        if (line.length() > 0 && line.indexOf("time=") > 0) {
          String context = line.substring(line.indexOf("time="));
          int index = context.indexOf("time=");
          String str = context.substring(index + 5, index + 9);
          Log.e(TAG, "time=: " + str);
          String result =
              new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date()) + ", " + hostName + ", " + str + "\r\n";
          Log.e(TAG, "result: " + result);
          write(pingFile, result);
        }
      }
    } catch (Exception ex) {
      System.out.println(ex.getMessage());
    }
  }
 /**
   *  Use java Call the console's ping Command, this is more reliable, also general, easy to use: pass in a ip , setting ping The number of times and timeout, you can determine whether or not according to the return value ping Pass. 
   */
  public static boolean ping2(String ipAddress, int pingTimes, int timeOut) {
    BufferedReader in = null;
    //  To be executed ping Command , This command is windows Format command 
    Runtime r = Runtime.getRuntime();
    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 = 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();
      }
    }
  }
  /**
   *  Stop running ping
   */
  public static void killPing() {
    if (process != null) {
      process.destroy();
      Log.e(TAG, "process: " + process);
    }
  }
  public static void write(File file, String content) {
    BufferedWriter out = null;
    Log.e(TAG, "file: " + file);
    try {
      out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
      out.write(content);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  //  If line Contain =18ms TTL=16 Typeface , Indicates that the ping Tong , Return 1, No to 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 = "appdlssl.dbankcdn.com"; //
   * System.out.println(ping(ipAddress)); ping02(); // System.out.println(ping(ipAddress, 5, 5000)); }
   */
}

Summarize


Related articles: