Hello,
Just a method in order to verify the accessibility of a host via PING command.
Examples With PING command
…With host name:
Microsoft Windows [version 10.0.14393]
(c) 2016 Microsoft Corporation. Tous droits réservés.
C:\Users\H>ping www.google.fr
Envoi d’une requête 'ping' sur www.google.fr [77.154.221.181] avec 32 octets de données :
Réponse de 77.154.221.181 : octets=32 temps=47 ms TTL=53
Réponse de 77.154.221.181 : octets=32 temps=319 ms TTL=53
Réponse de 77.154.221.181 : octets=32 temps=51 ms TTL=53
Statistiques Ping pour 77.154.221.181:
Paquets : envoyés = 3, reçus = 3, perdus = 0 (perte 0%),
Durée approximative des boucles en millisecondes :
Minimum = 47ms, Maximum = 319ms, Moyenne = 139ms
…With IP:
C:\Users\H>ping 77.154.221.181
Envoi d’une requête 'Ping' 77.154.221.181 avec 32 octets de données :
Réponse de 77.154.221.181 : octets=32 temps=56 ms TTL=53
Réponse de 77.154.221.181 : octets=32 temps=341 ms TTL=53
Réponse de 77.154.221.181 : octets=32 temps=51 ms TTL=53
Statistiques Ping pour 77.154.221.181:
Paquets : envoyés = 3, reçus = 3, perdus = 0 (perte 0%),
Durée approximative des boucles en millisecondes :
Minimum = 51ms, Maximum = 341ms, Moyenne = 149ms
Java Source Code
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;
}
int nb_try = 10;
for (int i = 0; i <nb_try; i++) {
Process myProcess = Runtime.getRuntime().exec(cmd);
myProcess.waitFor();
if(myProcess.exitValue() == 0) {
return true;
}else{
Thread.sleep(250); // Sleep 250 ms
}
}
return false;
} catch( Exception e ) {
e.printStackTrace();
return false;
}
}
… main test method:
public static void main(String[] args) {
if(isReachableByPing("www.google.fr")){
System.out.println("The host 'www.google.fr' is reachable by ping command.");
}else{
System.out.println("The host 'www.google.fr' is NOT reachable by ping command.");
}
if(isReachableByPing("77.154.221.181")){
System.out.println("The host '77.154.221.181' is reachable by ping command.");
}else{
System.out.println("The host '77.154.221.181' is NOT reachable by ping command.");
}
}
…outputs:
The host 'www.google.fr' is reachable by ping command. The host '77.154.221.181' is reachable by ping command.
That’s all!!!
Huseyin OZVEREN
