/**
* 测试设备网络状态
*
* @return boolean
* @throws Exception
*/
private static boolean connectTest() throws Exception {
String OS = System.getProperty("os.name").toLowerCase();
int pingTimes = 4;
String pingCommand = "";
if (OS.indexOf("windows")>=0) {
pingCommand = "ping " + ip + " -n " + pingTimes;
} else {
pingCommand = "ping " + "-c " + pingTimes + " " + ip;
}
boolean status = isReachable(pingCommand, pingTimes);
if (!status) {
throw new Exception("设备不能连接(ping 不通!!!)");
}
return status;
}
/** * 测试是否能ping通
* * @param server
* * @param timeout
* * @return */
private static boolean isReachable(String pingCommand, int pingTimes) {
BufferedReader in = null;
Runtime r = Runtime.getRuntime();
try {
// 执行命令并获取输出
System.out.println(pingCommand);
Process p = r.exec(pingCommand);
if (p == null) {
return false;
}
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
// 逐行检查输出,计算类似出现=23ms TTL=62字样的次数
int connectedCount = 0;
String line = null;
while ((line = in.readLine()) != null) {
connectedCount += getCheckResult(line);
}
// 如果出现类似=23ms TTL=62这样的字样,出现的次数=测试次数则返回真
return connectedCount == pingTimes;
} catch (Exception ex) {
ex.printStackTrace();
// 出现异常则返回假
return false;}
finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
分享到:
2015-01-20 12:45
浏览 3061
评论