Detecting Internet Connection Using Java
In this article, We are going to see how to check the internet connection using java. We are going to check if the internet is connected or not using Java Code.

We are going to connect to an URL using URL in java and if it gets connected then internet is connected, if not there is no internet connection.

There are various other ways to check internet connection, Here we are going to see 2 ways to check the internet connection.

Method 1:

public class InternetConCheck 
{
   public static void main(String[] args) throws Exception 
   {
        
       try 
       {
            URL url = new URL("http://www.google.com");
            URLConnection connection = url.openConnection();
            connection.connect();   
            System.out.println("Internet Connected");               
       } 
       
       catch (Exception e) 
       {      
            System.out.println("Sorry, No Internet Connection");                                                                 
       }                    
    }
}

In this code, We are trying to connect to google.com, if the connection is success – Internet is connected and we will get an output “Internet Connected”, If there is no internet connection, We will get an error message from catch block.

Output:
op1

Method 2:
In Method 2, We are going to use Process from the package java.lang.object

getRuntime() – Returns runtime object associated with the current java application. Most of the methods in runtime are instance methods and invoked with current runtime object. (Java Runtime)

process.waitFor() – Makes the thread wait until the process represented by process object is terminated. This method depends on subprocess too. If the subprocess is terminated it will return immediately, if not the calling thread will be blocked until the subprocess terminates. (Java Process)

public class CheckInternetCon 
{
   public static void main(String[] args) throws Exception 
   { 
      Process process = java.lang.Runtime.getRuntime().exec("ping www.google.com");
      System.out.println(process.waitFor());               
    }
}

The output will be 0(Zero) if the internet is connected and it will be 1(One) if the internet is not connected

Output:
op2

 

By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *