check for internet connection

hi

i have some problem in finding whether net connection is established or not

is there anything wromg in my code

import java.net.*;

import java.io.*;

/**

*

* @author prasanna

*/

public class ConnectionDetector {

/** Creates a new instance of ConnectionDetector */

public ConnectionDetector() {

}

public static void main(String arr[])

{

ConnectionDetector c =new ConnectionDetector();

try

{

c.detect();

}

catch(Exception e)

{

System.out.println(""+e);

e.printStackTrace();

}

}

public void detect() throws IOException

{

HttpURLConnection httpCon=null;

URL hp=null;

int statusCode;

String statusMessage;

try

{

System.out.println("inside try");

hp= new URL("http://www.google.com");

httpCon=(HttpURLConnection)hp.openConnection();

System.out.println("HOST"+ hp.getHost());

statusCode = httpCon.getResponseCode();

statusMessage=httpCon.getResponseMessage();

System.out.println(""+statusCode);

System.out.println(""+statusMessage);

if(statusCode==200)

{

System.out.println("Connected to ISP");

}

else if(statusCode==-1)

{

System.out.println("Cant connect to ISP["+statusMessage+"]");

}

else

{

System.out.println("ISP connected but different status["+statusMessage+"]");

}

}

catch(MalformedURLException e)

{

System.out.println(" - "+e);

}

catch(UnknownHostException e)

{

System.out.println("Network Cable Unplugged - "+e);

}catch(NoRouteToHostException e)

{

System.out.println("Network Cable Unplugged - "+e);

}

catch(Exception e)

{

System.out.println("- "+e);

//e.printStackTrace();

}

}//end of detect method

}

plz help me to find a solution

[1992 byte] By [prasannaramkumara] at [2007-10-3 4:44:20]
# 1

There is no good solution as the phrase 'connected to the Internet' doesn't have a well-defined meaning. This because (a) you don't connect to the Internet, you connect to a specific host, via your ISP, and (b) the Internet isn't a well-defined concept for this purpose either.

You could try InetAddress.isReachable() to www.yahoo.com or some other well-known site. The trouble is that if you are dealing with modem connections this is likely to establish the connection, and it's generally only in the case of modem connections that you're interested in this 'connected to the Internet' state at all.

ejpa at 2007-7-14 22:48:30 > top of Java-index,Core,Core APIs...
# 2
thanks for ur suggestion
prasannaramkumara at 2007-7-14 22:48:30 > top of Java-index,Core,Core APIs...
# 3
but this code also retruns false InetAddress addr = InetAddress.getByName("google.com");System.out.println("CHECK" + addr.isReachable(1000));
prasannaramkumara at 2007-7-14 22:48:30 > top of Java-index,Core,Core APIs...