Checking internet connectivity in Java


Internet connectivity can be checked using java.net.URL and java.net.URLConnection class. Following are the required steps.

  • Create a URL object and pass it the URL say Google

  • Call URL.openConnection() method to get a URLConnection object.

  • Call URLConnection.connect() method to check the internet connectivity. connect() method opens a communications link to the resource referenced by the passed URL if a connection has not already been established.

Example

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Tester {
   public static void main(String[] args) {
      try {
         URL url = new URL("http://www.google.com");
         URLConnection connection = url.openConnection();
         connection.connect();
         System.out.println("Internet is connected");
      } catch (MalformedURLException e) {
         System.out.println("Internet is not connected");
      } catch (IOException e) {
         System.out.println("Internet is not connected");
      }
   }
}

Output

Internet is connected

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 18-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements