Android中實現(xiàn)ping功能的多種方法詳解
使用java來實現(xiàn)ping功能。 并寫入文件。為了使用java來實現(xiàn)ping的功能,有人推薦使用java的 Runtime.exec()方法來直接調用系統(tǒng)的Ping命令,也有人完成了純Java實現(xiàn)Ping的程序,使用的是Java的NIO包(native io, 高效IO包)。但是設備檢測只是想測試一個遠程主機是否可用。所以,可以使用以下三種方式來實現(xiàn):
1. Jdk1.5的InetAddresss方式
自從Java 1.5,java.net包中就實現(xiàn)了ICMP ping的功能。
使用時應注意,如果遠程服務器設置了防火墻或相關的配制,可能會影響到結果。另外,由于發(fā)送ICMP請求需要程序對系統(tǒng)有一定的權限,當這個權限無法滿足時, isReachable方法將試著連接遠程主機的TCP端口 7(Echo)。代碼如下:
public static boolean ping(String ipAddress) throws Exception {
int timeOut = 3000; // 超時應該在3鈔以上
boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut); // 當返回值是true時,說明host是可用的,false則不可。
return status;
}
2. 最簡單的辦法,直接調用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調用控制臺執(zhí)行ping命令
具體的思路是這樣的:
通過程序調用類似“ping 127.0.0.1 -n 10 -w 4”的命令,這命令會執(zhí)行ping十次,如果通順則會輸出類似“來自127.0.0.1的回復: 字節(jié)=32 時間<1ms TTL=64”的文本(具體數字根據實際情況會有變化),其中中文是根據環(huán)境本地化的,有些機器上的中文部分是英文,但不論是中英文環(huán)境, 后面的“<1ms TTL=62”字樣總是固定的,它表明一次ping的結果是能通的。如果這個字樣出現(xiàn)的次數等于10次即測試的次數,則說明127.0.0.1是百分之百能連通的。
技術上:具體調用dos命令用Runtime.getRuntime().exec實現(xiàn),查看字符串是否符合格式用正則表達式實現(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())); // 逐行檢查輸出,計算類似出現(xiàn)=23ms TTL=62字樣的次數
int connectedCount = 0;
String line = null;
while ((line = in.readLine()) != null) {
connectedCount += getCheckResult(line);
} // 如果出現(xiàn)類似=23ms TTL=62這樣的字樣,出現(xiàn)的次數=測試次數則返回真
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字樣,說明已經ping通,返回1,否則返回0.
private static int getCheckResult(String line) { // System.out.println("控制臺輸出的結果為:"+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. 實現(xiàn)程序一開始就ping,運行完之后接受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; // 超時應該在3鈔以上
boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut); // 當返回值是true時,說明host是可用的,false則不可。
return status;
}
/**
* 使用java調用cmd命令,這種方式最簡單,可以把ping的過程顯示在本地。ping出相應的格式
* @param url
* @throws Exception
*/
public static void ping1(String url) throws Exception {
String line = null;
// 獲取主機名
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調用控制臺的ping命令,這個比較可靠,還通用,使用起來方便:傳入個ip,設置ping的次數和超時,就可以根據返回值來判斷是否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;
}
// 逐行檢查輸出,計算類似出現(xiàn)=23ms TTL=62字樣的次數
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)的次數=測試次數則返回真
return connectedCount == pingTimes;
} catch (Exception ex) {
ex.printStackTrace(); // 出現(xiàn)異常則返回假
return false;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 停止運行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字樣,說明已經ping通,返回1,否則返回0.
private static int getCheckResult(String line) { // System.out.println("控制臺輸出的結果為:"+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)); }
*/
}
總結
到此這篇關于Android中實現(xiàn)ping功能的多種方法詳解的文章就介紹到這了,更多相關android ping 功能內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Android Studio使用教程(六):Gradle多渠道打包
這篇文章主要介紹了Android Studio使用教程(六):Gradle多渠道打包,本文講解了友盟多渠道打包、assemble結合Build Variants來創(chuàng)建task、完整的gradle腳本等內容,需要的朋友可以參考下2015-05-05
Android Studio使用教程(五):Gradle命令詳解和導入第三方包
這篇文章主要介紹了Android Studio使用教程(五):Gradle命令詳解和導入第三方包,本文講解了導入Android Studio、Gradle常用命令等內容,需要的朋友可以參考下2015-05-05
Android音頻錄制MediaRecorder之簡易的錄音軟件實現(xiàn)代碼
這篇文章主要介紹了Android音頻錄制MediaRecorder之簡易的錄音軟件實現(xiàn)代碼,有需要的朋友可以參考一下2014-01-01
Android讀取本地json文件的方法(解決顯示亂碼問題)
這篇文章主要介紹了Android讀取本地json文件的方法,結合實例形式對比分析了解決顯示亂碼問題的方法,需要的朋友可以參考下2016-06-06

