I want to get the ping execution time and result in string after ping host. How can I do it?
This is how I used it -
private static void checkPing(String hostName) {
String[] command = { "cmd.exe", "/C", "ping " + hostName };
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader buff = new BufferedReader(new InputStreamReader(p.getInputStream()));
String readline;
while ((readline = buff.readLine()) != null) {
if (readline.contains("Reply")) {
System.out.println("Pinged " + hostName + " in : "
+ readline.substring(readline.indexOf("time=") + 5, readline.indexOf("ms")) + " ms");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Gives you the exact (reliable) ping latency in milliseconds for each ping request. You can then add the four of them, if required
long currentTime = System.currentTimeMillis();
boolean isPinged = InetAddress.getByName(servername).isReachable(2000); // 2 seconds
currentTime = System.currentTimeMillis() - currentTime;
if(isPinged) {
System.out.println("pinged successfully in "+ currentTime+ "millisecond");
} else {
System.out.println("PIng failed.");
}
But this will use ICMP ping only in windows system.
did you check this http://docs.oracle.com/javase/1.4.2/docs/guide/nio/example/Ping.java
and
http://www.java2s.com/Code/JavaAPI/java.net/InetAddressisReachableinttimeout.htm
long start = System.currentTimeMillis();
long ping;
String[] command = { "cmd.exe", "/C", "ping 192.168.1.101" };
commandProcess = Runtime.getRuntime().exec(command);
BufferedReader buffy = new BufferedReader(new InputStreamReader(commandProcess.getInputStream()));
String readline;
while((readline = buffy.readLine())!=null){
System.out.println(readline);
if(readline.contains("reply")){
long ping = System.currentTimeMillis();
System.out.println("Pinged in:"+ ping);
}
}
long end = System.currentTimeMillis();
String done = "Completed in times:" +start + ping +end;