<tutorialjinni.com/>

Check Internet Connection in JAVA Example

Posted Under: JAVA, Programming on Feb 29, 2016
With the growth of Internet of Things (IoTs) remain connected to the internet is mandatory any disconnection will result in an unexpected outcome. Therefore it is very important to write such logic in code that can handle such situations and prompt immediately about the unavailability of the internet.

This tutorial outline some of the ways by which one can check the internet presence from a JAVA Application. There is no definitive way of finding connectivity in java.



Internet Connectivity Checking Using Ping

/**
 * @author Originative
 */
public class InternetCheck {
    public static void main(String nix[]){
        try{
            Runtime run=Runtime.getRuntime();
            Process proc = run.exec("ping -n 1 208.67.222.222");
            int returnVal = proc.waitFor();
            boolean connected = (returnVal==0);
            System.out.println("Connected ? "+connected);
        }
        catch(Exception ex){
            System.out.println(ex);
        }
    }
}
This method work in windows. Here we check internet connectivity by running a simple ping to OpenDNS's IP. If it is successful 0 is returned else 2. Here we only send 1 ICMP packet. It can be increased by simply changing ping -n _ANY_NUMBER_OF_PINGS_ 208.67.222.222.

Internet Connectivity Checking Using JAVA Sockets

import java.net.*;

/**
 * @author Originative
 */
public class InternetCheck {
    public static void main(String nix[]){
        try{
            String host="redhat.com";
            int port=80;
            int timeOutInMilliSec=5000;// 5 Seconds
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(host, port), timeOutInMilliSec);
            System.out.println("Internet is Available");
        }
        catch(Exception ex){
            System.out.println("No Connectivity");
        }
    }
}
This is a cross platform solution and a flexible too. This method gives liberty to check connectivity on any port. It can also give false positives as firewall might block some ports.

Internet Connectivity Checking Using URL Connection

import java.net.*;

/**
 * @author Originative
 */
public class InternetCheck {
    public static void main(String nix[]){
        try{
            int timeOutInMilliSec=5000;// 5 Seconds
            URL url = new URL("http://www.redhat.com/");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("HEAD");
            conn.setConnectTimeout(timeOutInMilliSec);
            conn.setReadTimeout(timeOutInMilliSec);
            int responseCode = conn.getResponseCode();
            if(200 <= responseCode && responseCode <= 399){
                System.out.println("Internet is Available");
            }
        }
        catch(Exception ex){
            System.out.println("No Connectivity");
        }
    }
}
HTTP HEAD Request Method is used here conn.setRequestMethod("HEAD"); as we do not want the content of the webpage we only want to know if we can reach there. The only problem where this approach fails is where the URL, one is trying to connect is down. This approach too is a cross platform solution.

If someone is on Windows and want an absolute result and able to use JNI then the function InternetGetConnectedState in the wininet.dll can be used to know exactly the state as windows have it.
© Tutorial Jinni