java.net.InetAddress.isReachable() not working

Before making some calls to my RESTful Web Services, I wanted to check if my remote Java application could reach the server. I tried to use the java.net.InetAddress.isReachable() method but it kept on failing. I was testing out my code on my Linux VM and stumbled upon this.

http://bordet.blogspot.com/2006/07/icmp-and-inetaddressisreachable.html

So apparently on Linux, it tries to perform a "ping" and if that fails it tries to open a TCP socket on port 7. Out of curiosity, I wanted to see if I could make more sense of this by looking at the source code. So I looked up the source code of the java.net.InetAddress class and I ended up in java.net.Inet4AddressImpl and the method isReachable(). After that it calls a native method isReachable0. I don't know what I'm doing at this point, but apparently that method is implemented in native code using JNI. I did a grep on my OpenJDK source directory and got this.

./jdk/make/java/net/mapfile-vers
./jdk/test/sun/tools/jhat/jmap.bin
./jdk/src/share/classes/java/net/Inet6AddressImpl.java
./jdk/src/share/classes/java/net/Inet4AddressImpl.java
./jdk/src/windows/native/java/net/Inet4AddressImpl.c
./jdk/src/windows/native/java/net/Inet6AddressImpl.c
./jdk/src/solaris/native/java/net/Inet4AddressImpl.c
./jdk/src/solaris/native/java/net/Inet6AddressImpl.c

So at this point I still don't know where the Linux implementation of that method is and I've wasted a good hour just messing around. So I decided to figure all that stuff out another day and I went with this snippet of code for finding out if an address is reachable.

try {
  URL url = new URL("http://www.google.com" );
  HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
  Object objData = urlConnect.getContent();
} catch(IOException e) {
  /** logging code here **/
  return false;
}

This works for me because if there is no internet or the server is down, it'll fail at urlConnect.getContent() and I'll know by catching the exception. So until I find a better solution, this should do the trick.