How to ping a host in Java
This guide applies to:
Java
Windows
Linux
Mac OS X
The Java function isReachable() will use ICMP ECHO requests if the privilege can be obtained, otherwise it will try to make a TCP connection on port 7 (echo protocol rfc862) of the destination host. In most situations, it will fall back to the echo service method.
This function make a real ICMP ECHO ping.
public static boolean isReachableByPing(String host) {
try{
String cmd = "";
if(System.getProperty("os.name").startsWith("Windows")) {
// For Windows
cmd = "ping -n 1 " + host;
} else {
// For Linux and OSX
cmd = "ping -c 1 " + host;
}
Process myProcess = Runtime.getRuntime().exec(cmd);
myProcess.waitFor();
if(myProcess.exitValue() == 0) {
return true;
} else {
return false;
}
} catch( Exception e ) {
e.printStackTrace();
return false;
}
}