Java 實現Ping 功能__Java
來源:互聯網
上載者:User
package com.hotent.monitorRecords.dateReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Pinger {
/** * 要ping的主機 */
private String remoteIpAddress;
/** * 設定ping的次數 */
private final int pingTimes;
/** * 設定逾時 */
private int timeOut;
/** * 建構函式 * * @param remoteIpAddress * @param pingTimes * @param timeOut */
public Pinger(String remoteIpAddress, int pingTimes, int timeOut) {
super();
this.remoteIpAddress = remoteIpAddress;
this.pingTimes = pingTimes;
this.timeOut = timeOut;
}
/** * 測試是否能ping通 * @param server * @param timeout * @return
* @throws UnsupportedEncodingException */
public boolean isReachable() throws UnsupportedEncodingException {
BufferedReader in = null;
Runtime r = Runtime.getRuntime();
// 將要執行的ping命令,此命令是windows格式的命令
String pingCommand = "ping " + remoteIpAddress + " -n " + pingTimes + " -w " + timeOut;
try {
// 執行命令並擷取輸出
System.out.println(pingCommand);
Process p = r.exec(pingCommand);
if (p == null) {
return false;
}
in = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
// 逐行檢查輸出,計算類似出現=23ms TTL=62字樣的次數
int connectedCount = 0;
String line = null;
while ((line = in.readLine()) != null) {
String str=new String (line.getBytes("GB2312"),"GBK");
System.out.println(str);
//System.out.println("getCheckResult(line)=="+getCheckResult(line));
connectedCount += getCheckResult(line);
}
// 如果出現類似=23ms TTL=62這樣的字樣,出現的次數=測試次數則返回真
//System.out.println("connectedCount=="+connectedCount);
return connectedCount == pingTimes;
} catch (Exception ex) {
ex.printStackTrace();
// 出現異常則返回假
return false;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/** * 若line含有=18ms TTL=16字樣,說明已經ping通,返回1,否則返回0.
* * * @param line * @return */
private static int getCheckResult(String line) {
// System.out.println("控制台輸出的結果為:"+line);
Pattern pattern = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)",
Pattern.CASE_INSENSITIVE);
//System.out.println("pattern.matcher(line)==="+pattern.matcher(line));
Matcher matcher = pattern.matcher(line);
//System.out.println("matcher==="+matcher);
while (matcher.find()) {
return 1;
}
return 0;
}
public static void main(String[] args) {
Pinger p = new Pinger("192.168.2.171", 10, 5000);
try {
System.out.println(p.isReachable());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}