I'm trying to use Java's isReachable() method to measure ping latency between my pc and a server. By far I've been using this method:
Process p1 = Runtime.getRuntime().exec("ping -n 1 " + indIP);
int pingValue = 0;
long t1 = System.currentTimeMillis();
try {
p1.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long t2 = System.currentTimeMillis();
int exit = p1.exitValue();
if (exit==0){
pingValue = (int) (t2-t1);
return pingValue;
}
else
return -1;
but I noticed that it returned a value higher than the ping value got by using CMD (approx +10ms).
So I tried to use the method provided by InetAddress, but the value seems completely wrong.
Here's the code:
String servername = "xx.xx.xx.xx";
InetAddress addr = InetAddress.getByName(servername);
long currentTime = System.currentTimeMillis();
boolean pingOK = addr.isReachable(2000);
currentTime = System.currentTimeMillis() - currentTime;
if(pingOK) {
System.out.println("Ping: "+ currentTime+ " ms");
} else {
System.out.println("Ping failed.");
}
If I try, for example, to ping a server via CMD i get 9-10ms, but this method returns a value 100 times higher for the same server or it does not work at all. I gave a look at other threads here on Stackoverflow, but I couldn't find anything to get my ping check more accurate.
Thanks in advance for your time.
EDIT: I got a more accurate value by defining another method to "measure" the system latency:
public static int getSysLatency() throws IOException{
long t3 = System.currentTimeMillis();
Process p2 = Runtime.getRuntime().exec("ping -n 1 127.0.0.1");
try {
p2.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t3 = System.currentTimeMillis()-t3;
return (int) t3;
}
The latency in this case should be <1ms, so I can get the system "delay" when Process p1 = Runtime.getRuntime().exec("ping -n 1 " + indIP);
is called.
Then I subtracted t3 to pingValue and I got a better latency value, that is almost the same displayed via CMD.