溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android中實(shí)現(xiàn)ping功能的多種方法詳解

發(fā)布時間:2020-08-29 07:40:39 來源:腳本之家 閱讀:583 作者:恬靜釋然 欄目:移動開發(fā)

使用java來實(shí)現(xiàn)ping功能。 并寫入文件。為了使用java來實(shí)現(xiàn)ping的功能,有人推薦使用java的 Runtime.exec()方法來直接調(diào)用系統(tǒng)的Ping命令,也有人完成了純Java實(shí)現(xiàn)Ping的程序,使用的是Java的NIO包(native io, 高效IO包)。但是設(shè)備檢測只是想測試一個遠(yuǎn)程主機(jī)是否可用。所以,可以使用以下三種方式來實(shí)現(xiàn):

1. Jdk1.5的InetAddresss方式

自從Java 1.5,java.net包中就實(shí)現(xiàn)了ICMP ping的功能。

使用時應(yīng)注意,如果遠(yuǎn)程服務(wù)器設(shè)置了防火墻或相關(guān)的配制,可能會影響到結(jié)果。另外,由于發(fā)送ICMP請求需要程序?qū)ο到y(tǒng)有一定的權(quán)限,當(dāng)這個權(quán)限無法滿足時, isReachable方法將試著連接遠(yuǎn)程主機(jī)的TCP端口 7(Echo)。代碼如下:

 public static boolean ping(String ipAddress) throws Exception {
    int timeOut = 3000; // 超時應(yīng)該在3鈔以上
    boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut); // 當(dāng)返回值是true時,說明host是可用的,false則不可。
    return status;
  }

2. 最簡單的辦法,直接調(diào)用CMD

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調(diào)用控制臺執(zhí)行ping命令

具體的思路是這樣的:
通過程序調(diào)用類似“ping 127.0.0.1 -n 10 -w 4”的命令,這命令會執(zhí)行ping十次,如果通順則會輸出類似“來自127.0.0.1的回復(fù): 字節(jié)=32 時間<1ms TTL=64”的文本(具體數(shù)字根據(jù)實(shí)際情況會有變化),其中中文是根據(jù)環(huán)境本地化的,有些機(jī)器上的中文部分是英文,但不論是中英文環(huán)境, 后面的“<1ms TTL=62”字樣總是固定的,它表明一次ping的結(jié)果是能通的。如果這個字樣出現(xiàn)的次數(shù)等于10次即測試的次數(shù),則說明127.0.0.1是百分之百能連通的。
技術(shù)上:具體調(diào)用dos命令用Runtime.getRuntime().exec實(shí)現(xiàn),查看字符串是否符合格式用正則表達(dá)式實(shí)現(xiàn)。代碼如下:

public static boolean ping2(String ipAddress, int pingTimes, int timeOut) { 
    BufferedReader in = null; 
    Runtime r = Runtime.getRuntime(); // 將要執(zhí)行的ping命令,此命令是windows格式的命令 
    String pingCommand = "ping " + ipAddress + " -n " + pingTimes  + " -w " + timeOut; 
    try {  // 執(zhí)行命令并獲取輸出 
      System.out.println(pingCommand);  
      Process p = r.exec(pingCommand);  
      if (p == null) {  
        return false;  
      }
      in = new BufferedReader(new InputStreamReader(p.getInputStream()));  // 逐行檢查輸出,計(jì)算類似出現(xiàn)=23ms TTL=62字樣的次數(shù) 
      int connectedCount = 0;  
      String line = null;  
      while ((line = in.readLine()) != null) {  
        connectedCount += getCheckResult(line);  
      }  // 如果出現(xiàn)類似=23ms TTL=62這樣的字樣,出現(xiàn)的次數(shù)=測試次數(shù)則返回真 
      return connectedCount == pingTimes; 
    } catch (Exception ex) {  
      ex.printStackTrace();  // 出現(xiàn)異常則返回假 
      return false; 
    } finally {  
      try {  
        in.close();  
      } catch (IOException e) {  
        e.printStackTrace();  
      } 
    }
  }
  //若line含有=18ms TTL=16字樣,說明已經(jīng)ping通,返回1,否則返回0.
  private static int getCheckResult(String line) { // System.out.println("控制臺輸出的結(jié)果為:"+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. 實(shí)現(xiàn)程序一開始就ping,運(yùn)行完之后接受ping,并寫入文件

完整代碼如下:

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的InetAddresss,代碼簡單
   * @param ipAddress
   * @throws Exception
   */
  public static boolean ping(String ipAddress) throws Exception {
    int timeOut = 3000; // 超時應(yīng)該在3鈔以上
    boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut); // 當(dāng)返回值是true時,說明host是可用的,false則不可。
    return status;
  }
  /**
   * 使用java調(diào)用cmd命令,這種方式最簡單,可以把ping的過程顯示在本地。ping出相應(yīng)的格式
   * @param url
   * @throws Exception
   */
  public static void ping1(String url) throws Exception {
    String line = null;
    // 獲取主機(jī)名
    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());
    }
  }
 /**
   * 使用java調(diào)用控制臺的ping命令,這個比較可靠,還通用,使用起來方便:傳入個ip,設(shè)置ping的次數(shù)和超時,就可以根據(jù)返回值來判斷是否ping通。
   */
  public static boolean ping2(String ipAddress, int pingTimes, int timeOut) {
    BufferedReader in = null;
    // 將要執(zhí)行的ping命令,此命令是windows格式的命令
    Runtime r = Runtime.getRuntime();
    String pingCommand = "ping " + ipAddress + " -n " + pingTimes + " -w " + timeOut;
    try {
      // 執(zhí)行命令并獲取輸出
      System.out.println(pingCommand);
      Process p = r.exec(pingCommand);
      if (p == null) {
        return false;
      }
      // 逐行檢查輸出,計(jì)算類似出現(xiàn)=23ms TTL=62字樣的次數(shù)
      in = new BufferedReader(new InputStreamReader(p.getInputStream()));
      int connectedCount = 0;
      String line = null;
      while ((line = in.readLine()) != null) {
        connectedCount += getCheckResult(line);
      }
      // 如果出現(xiàn)類似=23ms TTL=62這樣的字樣,出現(xiàn)的次數(shù)=測試次數(shù)則返回真
      return connectedCount == pingTimes;
    } catch (Exception ex) {
      ex.printStackTrace(); // 出現(xiàn)異常則返回假
      return false;
    } finally {
      try {
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  /**
   * 停止運(yùn)行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();
      }
    }
  }
  // 若line含有=18ms TTL=16字樣,說明已經(jīng)ping通,返回1,否則返回0.
  private static int getCheckResult(String line) { // System.out.println("控制臺輸出的結(jié)果為:"+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)); }
   */
}

總結(jié)

到此這篇關(guān)于Android中實(shí)現(xiàn)ping功能的多種方法詳解的文章就介紹到這了,更多相關(guān)android ping 功能內(nèi)容請搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI