欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2020年03月18日 11:03:31   作者:恬靜釋然  
這篇文章主要介紹了Android中實(shí)現(xiàn)ping功能的多種方法詳解,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

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

1. Jdk1.5的InetAddresss方式

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

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

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

2. 最簡(jiǎn)單的辦法,直接調(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)用控制臺(tái)執(zhí)行ping命令

具體的思路是這樣的:
通過(guò)程序調(diào)用類(lèi)似“ping 127.0.0.1 -n 10 -w 4”的命令,這命令會(huì)執(zhí)行ping十次,如果通順則會(huì)輸出類(lèi)似“來(lái)自127.0.0.1的回復(fù): 字節(jié)=32 時(shí)間<1ms TTL=64”的文本(具體數(shù)字根據(jù)實(shí)際情況會(huì)有變化),其中中文是根據(jù)環(huán)境本地化的,有些機(jī)器上的中文部分是英文,但不論是中英文環(huán)境, 后面的“<1ms TTL=62”字樣總是固定的,它表明一次ping的結(jié)果是能通的。如果這個(gè)字樣出現(xiàn)的次數(shù)等于10次即測(cè)試的次數(shù),則說(shuō)明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ì)算類(lèi)似出現(xiàn)=23ms TTL=62字樣的次數(shù) 
      int connectedCount = 0;  
      String line = null;  
      while ((line = in.readLine()) != null) {  
        connectedCount += getCheckResult(line);  
      }  // 如果出現(xiàn)類(lèi)似=23ms TTL=62這樣的字樣,出現(xiàn)的次數(shù)=測(cè)試次數(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字樣,說(shuō)明已經(jīng)ping通,返回1,否則返回0.
  private static int getCheckResult(String line) { // System.out.println("控制臺(tái)輸出的結(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)程序一開(kāi)始就ping,運(yùn)行完之后接受ping,并寫(xiě)入文件

完整代碼如下:

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,代碼簡(jiǎn)單
   * @param ipAddress
   * @throws Exception
   */
  public static boolean ping(String ipAddress) throws Exception {
    int timeOut = 3000; // 超時(shí)應(yīng)該在3鈔以上
    boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut); // 當(dāng)返回值是true時(shí),說(shuō)明host是可用的,false則不可。
    return status;
  }
  /**
   * 使用java調(diào)用cmd命令,這種方式最簡(jiǎn)單,可以把ping的過(guò)程顯示在本地。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)用控制臺(tái)的ping命令,這個(gè)比較可靠,還通用,使用起來(lái)方便:傳入個(gè)ip,設(shè)置ping的次數(shù)和超時(shí),就可以根據(jù)返回值來(lái)判斷是否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ì)算類(lèi)似出現(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)類(lèi)似=23ms TTL=62這樣的字樣,出現(xiàn)的次數(shù)=測(cè)試次數(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字樣,說(shuō)明已經(jīng)ping通,返回1,否則返回0.
  private static int getCheckResult(String line) { // System.out.println("控制臺(tái)輸出的結(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論