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; } }
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; } }
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!