0

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.

3
  • 2
    Is this an SQA question? Or would it be better asked elsewhere? – Joe Strazzere May 7 '13 at 11:31
  • The above code will fail if your NIC is up but Google, your router, or your ISP is down. – user246 May 7 '13 at 15:06
  • I would migrate this to SO, but it is a duplicate, so I'm simply closing it. I do hope Alex helped solve your problem, though!. – corsiKa May 25 '13 at 0:42
5

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) {}
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.