Why inetAddress.isReachable() Returns False Despite Successful Ping
Your code retrieves an InetAddress instance for a specific IP address and then invokes its isReachable() method with a timeout of 1000 milliseconds:
InetAddress byName = InetAddress.getByName("173.39.161.140"); System.out.println(byName); System.out.println(byName.isReachable(1000));
However, surprisingly, isReachable() returns false, even though you can successfully ping the IP address.
Cause and Solution
Cause:
isReachable() doesn't rely on the ping command or any other operating system-specific tools. Instead, it uses the ICMP protocol to check if the host is reachable by sending ICMP Echo Request messages and waiting for ICMP Echo Reply messages. Some systems may block ICMP traffic, leading to the isReachable() method's failure.
Solution:
To determine reachability without relying on isReachable(), you can use the following Java code:
private static boolean isReachable(String addr, int openPort, int timeOutMillis) { // Any Open port on other machine // openPort = 22 - ssh, 80 or 443 - webserver, 25 - mailserver etc. try (Socket soc = new Socket()) { soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis); return true; } catch (IOException ex) { return false; } }
This method attempts to connect to the specified open port on the remote machine. If the connection succeeds, it means the host is reachable. The open port can be any port that is typically accessible, such as 22 for SSH, 80 for HTTP, or 443 for HTTPS.
The above is the detailed content of Why Does `InetAddress.isReachable()` Return False Even Though Ping Succeeds?. For more information, please follow other related articles on the PHP Chinese website!