Tuesday, November 28, 2006

Snippet://java/internet connectivity

The following code checks if internet can be accessed. Note, this is not a ping. The Java Socket class isn't capable of such low level function. However, since JDK5, Java java.net.InetAddress.isReachable(int) can be used to check if a server is reachable or not.

isReachable() will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host. But most Internet sites have disabled the service or blocked the requests (except some university such as web.mit.edu).



public static boolean checkinternet(String url) {
try {
InetAddress address = InetAddress.getByName(url);
System.out.println("Name: " + address.getHostName());
System.out.println("Addr: " + address.getHostAddress());
System.out.println("Reach: " + address.isReachable(1000));
} catch (UnknownHostException e) {
System.err.println("Unable to lookup " + url);
} catch (IOException e) {
System.err.println("Unable to reach " + url);
}
}

No comments: