版权声明:本文为Zhang Phil原创文章,请不要转载! https://blog.csdn.net/zhangphil/article/details/82996881
Java实现TCP/IP的ping连通性
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class TestClass {
public static void main(String[] args) {
String netAddress = "www.csdn.net";
java_ping(netAddress);
}
/**
* Java平台上,用Java实现并运行起来的TCP/IP中的ping。 ping之后的结果输出到StringBuffer中。
*/
private static void java_ping(String ip) {
Runtime runtime = Runtime.getRuntime();
Process process;
try {
process = runtime.exec("ping " + ip);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println("ping命令结果输出:" + sb);
is.close();
isr.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出结果:
ping命令结果输出:正在 Ping www.csdn.net [47.95.164.112] 具有 32 字节的数据:来自 47.95.164.112 的回复: 字节=32 时间=52ms TTL=90来自 47.95.164.112 的回复: 字节=32 时间=52ms TTL=90来自 47.95.164.112 的回复: 字节=32 时间=52ms TTL=90来自 47.95.164.112 的回复: 字节=32 时间=52ms TTL=9047.95.164.112 的 Ping 统计信息: 数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),往返行程的估计时间(以毫秒为单位): 最短 = 52ms,最长 = 52ms,平均 = 52ms