java 测试网络_java Ping操作(测试网络)

本文介绍了如何在Windows和Unix系统中使用ping命令进行网络连通性测试,包括ping命令的构造、执行流程及异常处理。通过实例展示了如何检查网络可达性,并捕获ping结果以判断设备是否能正常连接。
摘要由CSDN通过智能技术生成

/**

* 测试设备网络状态

*

* @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();

}

}

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2015-01-20 12:45

浏览 3061

评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值