问题
I want to get the ping execution time and result in string after ping host. How can I do it?
回答1:
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.
回答2:
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
回答3:
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;
来源:https://stackoverflow.com/questions/8816870/i-want-to-get-the-ping-execution-time-and-result-in-string-after-ping-host