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

Why Does `InetAddress.isReachable()` Return False Even Though Ping Succeeds?

Mary-Kate Olsen
Release: 2024-12-07 01:58:12
Original
1001 people have browsed it

Why Does `InetAddress.isReachable()` Return False Even Though Ping Succeeds?

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

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

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!

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