Reputation: 297
So I have been using isReachable to "ping" an address in my java code. This block of code is what everyone seems to use:
try
{
InetAddress address = InetAddress.getByName("172.16.2.0");
// Try to reach the specified address within the timeout
// periode. If during this periode the address cannot be
// reach then the method returns false.
boolean reachable = address.isReachable(10000);
System.out.println("Is host reachable? " + reachable);
} catch (Exception e)
{
e.printStackTrace();
}
My issue is that no matter what I use for my IP address it always returns true. Even if I change it to empty string. Any ideas why?
Upvotes: 3
Views: 5188
Reputation: 15244
A way to check if some address is reachable, via java.net.InetAddress.isReachable() methods. The implementation of these methods goes native and tries to do its best to "ping" the address represented by the InetAddress.
Surprisingly, there are many differences between the Windows and the Linux/Unix implementation of java.net.InetAddress.isReachable()
.
Windows, as strange as it seems, does not officially support an ICMP "ping" system call. The Java SE 5 implementation hence tries to open a TCP socket on port 7 (the echo service) and hopes to get some sort of reply.
Linux/Unix, instead, supports an ICMP "ping" system call. So the implementation of java.net.InetAddress.isReachable() first tries to perform the "ping" system call; if this fails, it falls back trying to open a TCP socket on port 7, as in Windows.
It turns out that in Linux/Unix the ping system call requires root privileges, so most of the times java.net.InetAddress.isReachable() will fail, because many Java programs are not run as root.
The correct approach is the ICMP protocol. This is what ping uses internally. It is recommended see THIS to gather knowledge and proceed.
FROM: Simone Bordet's Blog
Upvotes: 2