I know that issues with pinging in Java have been discussed many times but after searching through numerous threads I haven't come up with a solution yet. In addition, my problem is specific.
I'm new to Java and I've heard that you can't do a real ping unless you use native code. Then I discovered the isReachable method which was supposed to solve most of the pinging issues.
My problem is that every time, on any host, this method needs >=1000ms to complete. In the following code, 'pinging' the localhost returns 1000ms in most cases, sometimes a bit more. But never under 1s.
public class NewMain {
static InetAddress ip;
public static void main(String[] args) throws Exception {
ip= InetAddress.getByName("localhost");
long start= System.currentTimeMillis();
boolean reachable= ip.isReachable(2000);
long end= System.currentTimeMillis();
if (reachable)
System.out.println(end-start+"ms");
}
}
From what I could find on this matter, some people got correct results with similar methods (~0ms) while some others got results similar to mine (~1000ms). I didn't try to implement my own ping() method yet because isReachable sounds just right for my needs, only if it worked right.
I would appreciate if you could run this code and post the results along with your JDK version.
I am using JDK 1.6.0 .