1

Possible Duplicate:
Detect internet Connection using Java
How to check if internet connection is present in java?

Following is my code to check whether PC has internet connectivity or not:

try{
    URL url = new URL("http://www.google.co.in");
    URLConnection connection = url.openConnection();
    connected = true;
}
catch(IOException ioe){
    connected = false;
    ioe.printStackTrace();
}

I want to know whether this a reliable and best method? Whenever there is no internet connectivity, an acception would be thrown and the value of boolean variable connected equals false.

Community
  • 1
  • 1
kunal18
  • 1,935
  • 5
  • 33
  • 58
  • 4
    possible duplicate of [Detect internet Connection using Java](http://stackoverflow.com/questions/1139547/detect-internet-connection-using-java) and [How to check if internet connection is present in java?](http://stackoverflow.com/questions/1402005) – Tomasz Nurkiewicz Oct 06 '12 at 16:55
  • Hint: `ping www.stackoverflow.com`. – Eng.Fouad Oct 06 '12 at 16:56
  • This method is not reliable! The value of connected is always true. Can someone explain me why!? – kunal18 Oct 06 '12 at 20:04

1 Answers1

0

Try using InetAddress.isReachable()

drewhannay
  • 1,030
  • 6
  • 12
  • How it is better than current method? – kunal18 Oct 06 '12 at 16:58
  • The specific intention of the method is to check if an address is reachable. Why duplicate functionality that already exists? Also, I'd recommend not just pinging google, but actually check the site you need to access. – drewhannay Oct 06 '12 at 17:00
  • Actually I don't want to access any particular website. I just want to know whether PC can connect to internet or not! – kunal18 Oct 06 '12 at 17:02
  • I tried using InetAddress.isReachable(); but it always returns false! Can anyone expalin?! – kunal18 Oct 06 '12 at 20:04