我希望通过这种方式获得2台PC之间的延迟时间:
currentTime = System.currentTimeMillis();
isPinged = InetAddress.getByName("192.168.6.18").isReachable(2000);
currentTime = System.currentTimeMillis() - currentTime;
System.out.println("----"+isPinged+":"+currentTime);
但结果总是“假”,除了“localhost”,我尝试将getByName("192.168.6.18")
更改为LAN的PC,或者像“www.facebook.com”这样的网站,但它没有效果
答案 0 :(得分:-3)
将此方法用于Windows PC
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
public Boolean ping(String ipaddress)
{
Runtime runtime = Runtime.getRuntime();
String cmds = "ping "+ipaddress;
System.out.println(cmds);
Process proc;
try {
proc = runtime.exec(cmds);
proc.getOutputStream().close();
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
while ((line = bufferedreader.readLine()) != null) {
if(line.contains("Reply from "+ipaddress+":"))
{
return true;
}
}
}catch (IOException e) {
e.printStackTrace();
}
return false;
}
有关详细信息,请参阅Ping class
对于Windows以外的PC,请使用
public Boolean IsReachable(String ipaddress) {
try {
final InetAddress host = InetAddress.getByName(ipaddress);
try {
return host.isReachable(3000);
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return false;
}