Java InetAddress.isReachable() timeout
Asked Answered
C

1

8

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()?

Comose answered 4/3, 2012 at 14:12 Comment(0)
P
6

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.

Primer answered 4/3, 2012 at 14:30 Comment(2)
Thanks, Essentially yes, I would like to connect to/check the hosts on port 10001 which is used by the devices I need to find. Could you possibly give an example of how to implement that known port check?Comose
Well, I don't go into implementing a non-blocking I/O (NIO) method. But I would say just create a Socket. Create a SocketAddress with the destination IP and port 10001. Then call socket.connect(SocketAddress, timeout) with the appropriate timeout. Catch TimeOutException. If the socket.connect() returns without exception, close the socket, you know that device is listening on 10001. For a NIO model, have a look at the Netty open-source project and examples.Primer

© 2022 - 2024 — McMap. All rights reserved.