Java程序中获取Ping的返回信息
工作中遇到了这个需求,就网上搜罗了下,做个记录。本代码只涉及执行Ping语句并输出返回信息,不深究其他内容。
代码如下:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Ping {
public static void main(String[] args) {
String pingStr = "ping -n 8 www.baidu.com";
BufferedReader br = null;
try {
Process p = Runtime.getRuntime().exec(pingStr);
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
StringBuilder sb=new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
运行输出如下:
正在 Ping www.a.shifen.com [61.135.169.125] 具有 32 字节的数据: 请求超时。 请求超时。 来自 61.135.169.125 的回复: 字节=32 时间=69ms TTL=47 来自 61.135.169.125 的回复: 字节=32 时间=69ms TTL=47 请求超时。 请求超时。 来自 61.135.169.125 的回复: 字节=32 时间=29ms TTL=47 来自 61.135.169.125 的回复: 字节=32 时间=28ms TTL=47 61.135.169.125 的 Ping 统计信息: 数据包: 已发送 = 8,已接收 = 4,丢失 = 4 (50% 丢失), 往返行程的估计时间(以毫秒为单位): 最短 = 28ms,最长 = 69ms,平均 = 48ms