Home >Java >javaTutorial >Why Does InetAddress.isReachable() Sometimes Return False Even When Ping Succeeds?

Why Does InetAddress.isReachable() Sometimes Return False Even When Ping Succeeds?

Barbara Streisand
Barbara StreisandOriginal
2024-12-02 09:18:10634browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn