How to Check my pc is having internet connection using java



  • I need to find whether my pc is connected to internet using java.From references, I found that using below code just verify whether NIC is up or down.

                 public static boolean isInternetReachable()
    {
        try {
            //make a URL to a known source
            URL url = new URL("http://www.google.com");
    
            //open a connection to that source
            HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
    
            //trying to retrieve data from the source. If there
            //is no connection, this line will fail
            Object objData = urlConnect.getContent();
            System.out.println("SUCCESSFUL INTERNET CONNECTION");
    
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
    
            System.out.println("CONNECTION FAILED");
            e.printStackTrace();
            return false;
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("CONNECTION FAILED");
            e.printStackTrace();
            return false;
        }
        return true;
    }
    

    Is there any way so that I can use methods like ping to required url and catch the reply.

    Thanks in advance.



  • There's a good thread here on Stack Overflow.

    Their answer is to use java sockets:

    Socket socket = null;
    boolean reachable = false;
    try {
        socket = new Socket(hostnameOrIP, 80);
        reachable = true;
    } finally {            
        if (socket != null) try { socket.close(); } catch(IOException e) {}
    }
    

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2