请问怎样用java发送ICMP包,实现ping,测量两个主机之间的延时
发布网友
发布时间:2022-05-27 16:52
我来回答
共1个回答
热心网友
时间:2023-11-05 04:28
网上搜的
三、ICMP Ping in Java(JDK 1.5 and above)
Programatically using ICMP Ping is a great way to establish that a server is up and running. Previously you couldn't do ICMP ping (what ping command does in Linux/Unix & Windows) in java without using JNI or exec calls. Here is a simple and reliable method to do ICMP pings in Java without using JNI or NIO.
String host = "172.16.0.2"
int timeOut = 3000; // I recommend 3 seconds at least
boolean status = InetAddress.getByName(host).isReachable(timeOut)
status is true if the machine is reachable by ping; false otherwise. Best effort is made to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.
In Linux/Unix you may have to suid the java executable to get ICMP Ping working, ECHO REQUESTs will be fine even without suid. However on Windows you can get ICMP Ping without any issues whatsoever.
四、最简单的办法,直接调用CMD
try
{
Runtime.getRuntime().exec("cmd /c start ping 127.0.0.1");
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
ping的过程可以显示在本地的办法
import java.io.*;
public class Ping
{
public static void main(String args[])
{
String line = null;
try
{
Process pro = Runtime.getRuntime().exec("ping 127.0.0.1 ");
BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
while ((line = buf.readLine()) != null)
System.out.println(line);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
五、模拟PING
利用InetAddress的isReachable方法可以实现ping的功能,里面参数设定超时时间,返回结果表示是否连上
try {
InetAddress address = InetAddress.getByName("192.168.0.113");
System.out.println(address.isReachable(5000));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
参考资料:http://blog.sina.com.cn/s/blog_4b00fd1b0100by7z.html