title: Java Quickly check for network connection
body: <p>My issue is fairly straightforward.  My program requires immediate notification if a network connection is lost.  I'm using Java 5, so I'm unable to use the very handy features of <a href="http://download.oracle.com/javase/6/docs/api/java/net/NetworkInterface.html" rel="noreferrer">NetworkInterface</a>.</p>
  
  <p>Currently I have two different methods of checking for a network connection:<br>
  (try..catches removed)  </p>
  
  <p>Method One:  </p>
  
  <pre><code>URL url = new URL("http://www.google.com");
  HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
  // trying to retrieve data from the source. If offline, this line will fail:
  Object objData = urlConnect.getContent();
  return true;
  </code></pre>
  
  <p>Method 2:</p>
  
  <pre><code>Socket socket = new Socket("www.google.com", 80);
  netAccess = socket.isConnected();
  socket.close();
  return netAccess;
  </code></pre>
  
  <p>However, both of these methods block until a Timeout is reached before returning false.  I need a method that will return immediately, but is compatible with Java 5.</p>
  
  <p>Thanks!</p>
  
  <p>EDIT:
  I forgot to mention that my program is reliant on IP addresses, not DNS names.  So checking for an error when resolving a host is out...</p>
  
  <p>2nd EDIT:</p>
  
  <p>Figured out a final solution using <a href="http://download.oracle.com/javase/6/docs/api/java/net/NetworkInterface.html" rel="noreferrer">NetworkInterface</a>:</p>
  
  <pre><code>Enumeration&lt;NetworkInterface&gt; eni = NetworkInterface.getNetworkInterfaces();
          while(eni.hasMoreElements()) {
              Enumeration&lt;InetAddress&gt; eia = eni.nextElement().getInetAddresses();
              while(eia.hasMoreElements()) {
                  InetAddress ia = eia.nextElement();
                  if (!ia.isAnyLocalAddress() &amp;&amp; !ia.isLoopbackAddress() &amp;&amp; !ia.isSiteLocalAddress()) {
                      if (!ia.getHostName().equals(ia.getHostAddress()))
                          return true;
                  }
              }
          }
  </code></pre>