Java InetAddress.isReachable() timeout

Jerome picture Jerome · Mar 4, 2012 · Viewed 9k times · Source

I am trying to find out if specific hosts on my network are reachable. My java code is as follows:

InetAddress adr = InetAddress.getByName(host);
if(adr.isReachable(3000)){
    System.out.println(host + " is reachable");
}

This works quite well, however if I lower the timeout to say 500ms instead, it will not designate the host reachable anymore. I plan to check quite a few hosts in a loop, so having a low timeout is quite important. If I ping the host manually from the windows command line, it takes less than 10ms.

So why does the Java method need a much higher timeout to succeed? Are there any alternatives to using isReachable()?

Answer

brettw picture brettw · Mar 4, 2012

It depends on what you mean by reachability. If you only what do find reachable hosts listening on specific ports, you can open a socket connection to that port (for example, finding all HTTP servers by checking port 80). Using InetAddress.isReachable() is implementation dependent. According to the javadoc, "A typical implementation will use ICMP ECHO REQUESTs". A "known port" check (like http(80), smb (445), etc.) using Java NIO (non-blocking I/O) can have higher performance. My company has a product that uses a "known port" scan to find boxes running Telnet or SSH, using NIO, and we can scan about 5000 IP/sec.