Take the 2-minute tour ×
Software Quality Assurance & Testing Stack Exchange is a question and answer site for software quality control experts, automation engineers, and software testers. It's 100% free, no registration required.

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.

share|improve this question
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
add comment

closed as off topic by corsiKa May 25 '13 at 0:41

Questions on Software Quality Assurance & Testing Stack Exchange are expected to relate to software quality assurance or testing within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

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) {}
}
share|improve this answer
add comment

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