Tuesday, November 11, 2008

Checking network connection using Java

At times it is required to check whether the machine is still connected to network or not. One way to find it using JDK1.6 by using the code is as below.
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
    NetworkInterface nic = interfaces.nextElement();
    System.out.print("Interface Name : [" + nic.getDisplayName() + "]");
    System.out.println(", Is connected : [" + nic.isUp() + "]");
}
Additionally several new useful methods such as isLoopBack(), isPointToPoint() and many more have been added in JDK 1.6 release. Refer to the Javadocs for more information on NetworkInterface class in java.net package.