I want to get the ping execution time and result in string after ping host

前端 未结 4 1981
醉梦人生
醉梦人生 2021-01-13 14:10

I want to get the ping execution time and result in string after ping host. How can I do it?

相关标签:
4条回答
  • 2021-01-13 14:13

    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

    0 讨论(0)
  • 2021-01-13 14:15
    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.

    0 讨论(0)
  • 2021-01-13 14:17

    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

    0 讨论(0)
  • 2021-01-13 14:29
    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;
    
    0 讨论(0)
提交回复
热议问题