Pinging a host in JDK1.5

JDK1.5 provides the functionality to test the reachability of a host. Before JDK 1.5, you had to implement this yourself (for example by sending UDP packets to the echo port (7) of the target machine).

Actually, the strategy of the implementation of isReachable is to try to use ICMP if it is available, or else to try to connect to the echo port.

This example shows you how the test the reachability of a host:

import java.net.*;

public class Main
{
   public static void main(String []args) throws Exception {
      if (args.length != 1) {
         System.out.println("Usage: java Main <host or ipaddress>");
         System.exit(1);
      }
      
      InetAddress inetAddress = InetAddress.getByName(args[0]);
      System.out.println(inetAddress);
      
      System.out.println(args[0] + " is reachable? " + inetAddress.isReachable(5000));
   }  
}