How To Check The Internet Connection In Java?

In this instructional exercise, we will figure out how to check our PC having an internet connection or not using simple Java code. If you want to ping a particular URL or website, then you first need to check if an internet connection available on your PC.

If you don’t know how to check our PC having an internet connection or not by java code or program, at that point you are at the correct spot.

Check An Internet Connection Of PC By Java Code

Let’s learn with some easy examples.

We can check internet connectivity using java by 2 methods:
a) By using methods of java URL and URL Connection classes.
b) By using getRuntime() method of Java Runtime class.

Let’s learn how to check an internet connection by the 1st method i.e.,
By using methods of java URL and URL Connection classes:




At first import java.net.URL and java.net.URLConnection packages. We can do it by:

import java.net.URL;
import java.net.URLConnection;

 

By importing these two packages will help you to use different classes of these packages and those classes are:
1) java URL class– provides methods that return diverse information like hostname, protocol, file name, etc of the URL.
2)java URLConnection class-It speaks to a connection among URL and application and can be utilized to peruse and compose information to the predefined asset alluded by the URL.
3)open Connection()-This technique for java URLConnection class opens the association with the predetermined URL.

The below code will help you out to write a java code to check an internet connection:

import java.net.URL;
import java.net.URLConnection; 

public class CheckInternetConnection{
 
public static void main(String[] args){
  
try 
{
        URL u = new URL("https://www.google.com");
 
        URLConnection conn = u.openConnection();
        conn.connect();   
 
        System.out.println("Internet connection established");   
            
 }catch (Exception e){
     
        System.out.println("No Internet Connection available, please connect with internet");     
                                                            
} 
}
}

Also, read:

 

If we run the above Java program, it will print “Internet connection established”. But if there is no internet connection available then it will show “Internet connection established” message.

I hope you have understood our code and you will able to implement it in your work.


Leave a Reply

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