我想获得ping执行时间并在ping主机后生成字符串

时间:2012-01-11 09:25:15

标签: java ping

我想获取ping执行时间并在ping主机后生成字符串。我该怎么办?

4 个答案:

答案 0 :(得分:5)

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.");
}

但是这只会在Windows系统中使用ICMP ping。

答案 1 :(得分:0)

答案 2 :(得分:0)

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;

答案 3 :(得分:0)

这就是我的用法-

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();
    }
}

为您提供每个ping请求的准确(可靠)ping延迟(以毫秒为单位)。 然后,您可以根据需要添加其中的四个