import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Ping {
public static void main(String[] args) throws IOException {
try {
String hostname = args[0];
int timeout = (args.length > 1)?Integer.parseInt(args[1]):2000;
InetAddress[] addresses = InetAddress.getAllByName(hostname);
for(InetAddress address : addresses) {
if (address.isReachable(timeout))
System.out.printf("%s is reachable%n", address);
else
System.out.printf("%s could not be contacted%n", address);
}
}
catch (UnknownHostException e) {
System.out.printf("Unknown host: %s%n", args[0]);
}
catch(IOException e) { System.out.printf("Network error: %s%n", e); }
catch (Exception e) {
// ArrayIndexOutOfBoundsException or NumberFormatException
System.out.println("Usage: java Ping <hostname> [timeout in ms]");
}
}
}
|