Monday, 14 November 2016

How to Check Internet Connection in Java?

Today we'll see how to check internet connectivity using Java. In java we can have several ways to check internet connection. But in our example we'll take ping command to for checking connectivity. We'll just execute the ping command using exec() method, if the exit value of process is 0 (Zero) then we can say internet connection is available else internet connection is not available.

Please note that this is not the only way to check internet connectivity. We can make use of .net package of Java also.

Lets look into the example -

package com.anjan.test;

public class CheckInternetDemo {

    public static String checkInternetConnection(String host) {
      try{
            String cmd = "";
            if(System.getProperty("os.name").startsWith("Windows"))

            {  
               // For Windows OS
               cmd = "ping -n 1 " + host;
            } else {
               // For Other OS - Linux
               cmd = "ping -c 1 " + host;
            }

            Process myProcess = Runtime.getRuntime().exec(cmd);
            myProcess.waitFor();

            if(myProcess.exitValue() == 0) {

                return "Available";
                           
            } else {

                return "Not Available";
            }

       } catch( Exception e ) {

          e.printStackTrace();
          return "Not Available";
       }
    }
   
    public static void main(String args[]){
        System.out.println("Internet Connection : "+
checkInternetConnection("www.google.com"));
    }
}




Output -


Internet Connection : Available

No comments:

Post a Comment