Home >Java >javaTutorial >Why Does InetAddress.isReachable() Sometimes Return False Even When Ping Succeeds?
Unveiling the Disconnect: Why InetAddress.isReachable() Reports Falsely
When attempting to determine the reachability of an IP address using InetAddress.isReachable(), users may encounter unexpected false responses despite being able to successfully ping the same address. This discrepancy can be attributed to limitations in the implementation of isReachable().
Unlike ping, which directly sends a network packet to the target IP, isReachable() relies on a platform-dependent mechanism known as ICMP (Internet Control Message Protocol) echo requests. If the ICMP request is not responded to within the specified timeout period, isReachable() returns false, even if the IP is still accessible.
Providing a Cross-Platform Solution
For a platform-independent solution that encompasses a range of connectivity checks, consider employing a technique that probes for open ports on the target machine. This approach leverages the fact that most devices possess open ports for services such as SSH, web servers, or mail servers.
Here's a code snippet that implements this method:
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; } }
By utilizing this technique, you gain the ability to determine reachability irrespective of the underlying platform, ensuring more consistent results.
The above is the detailed content of Why Does InetAddress.isReachable() Sometimes Return False Even When Ping Succeeds?. For more information, please follow other related articles on the PHP Chinese website!