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

前端 未结 4 2006
醉梦人生
醉梦人生 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

提交回复
热议问题