Android中實現(xiàn)ping功能的多種方法詳解
使用java來實現(xiàn)ping功能。 并寫入文件。為了使用java來實現(xiàn)ping的功能,有人推薦使用java的 Runtime.exec()方法來直接調(diào)用系統(tǒng)的Ping命令,也有人完成了純Java實現(xiàn)Ping的程序,使用的是Java的NIO包(native io, 高效IO包)。但是設(shè)備檢測只是想測試一個遠(yuǎn)程主機是否可用。所以,可以使用以下三種方式來實現(xiàn):
1. Jdk1.5的InetAddresss方式
自從Java 1.5,java.net包中就實現(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)程主機的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ù)實際情況會有變化),其中中文是根據(jù)環(huán)境本地化的,有些機器上的中文部分是英文,但不論是中英文環(huán)境, 后面的“<1ms TTL=62”字樣總是固定的,它表明一次ping的結(jié)果是能通的。如果這個字樣出現(xiàn)的次數(shù)等于10次即測試的次數(shù),則說明127.0.0.1是百分之百能連通的。
技術(shù)上:具體調(diào)用dos命令用Runtime.getRuntime().exec實現(xiàn),查看字符串是否符合格式用正則表達(dá)式實現(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字樣的次數(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. 實現(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; // 超時應(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;
// 獲取主機名
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;
}
// 逐行檢查輸出,計算類似出現(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();
}
}
}
/**
* 停止運行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中實現(xiàn)ping功能的多種方法詳解的文章就介紹到這了,更多相關(guān)android ping 功能內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用smsmanager實現(xiàn)后臺發(fā)送短信示例
這篇文章主要介紹了android利用SmsManager可以實現(xiàn)后臺發(fā)送短信的方法,最近有使用說明,大家可以參考使用2014-01-01
Android TextView 設(shè)置字體大小的方法
這篇文章主要介紹了Android TextView 設(shè)置字體大小的方法的相關(guān)資料,需要的朋友可以參考下2016-02-02
Android AsyncTask的缺陷和問題總結(jié)
這篇文章主要介紹了Android AsyncTask的缺陷和問題總結(jié)的相關(guān)資料,需要的朋友可以參考下2017-03-03
Android使用LinearLayout設(shè)置邊框
這篇文章主要介紹了Android如何使用LinearLayout設(shè)置邊框,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09
Android中通過AsyncTask類來制作炫酷進(jìn)度條的實例教程
這篇文章主要介紹了Android中通過AsyncTask來制作炫酷進(jìn)度條的實例教程,借助AsyncTask類的線程操作方法來管理異步任務(wù),需要的朋友可以參考下2016-05-05

