Home > Java > javaTutorial > Why Does InetAddress.isReachable() Sometimes Differ from Ping Results?

Why Does InetAddress.isReachable() Sometimes Differ from Ping Results?

Mary-Kate Olsen
Release: 2024-12-01 01:55:10
Original
315 people have browsed it

Why Does InetAddress.isReachable() Sometimes Differ from Ping Results?

Understanding InetAddress.isReachable() Results

The InetAddress class provides a mechanism to obtain information about network addresses. One of its methods, isReachable(), checks if a host is reachable from the local machine. However, users may encounter discrepancies between pinging an IP address and the result of InetAddress.isReachable().

Platform Independence for Reachability Testing

For a platform-independent solution, consider using the following code, which requires knowledge of an open port on the target machine:

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;
    }
}
Copy after login
Copy after login

Updated Succinct Version

Based on a recent comment, here is a more concise version of the above 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;
    }
}
Copy after login
Copy after login

This solution is independent of the platform and provides reliable reachability results.

The above is the detailed content of Why Does InetAddress.isReachable() Sometimes Differ from Ping Results?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template