以ms为单位显示IP地址的实时ping

时间:2017-06-10 11:05:04

标签: java

我正在尝试创建一个ping工具,以毫秒为单位显示IP地址的ping。我已经创建了一个显示输出的程序,就像在命令提示符中完成的一样。

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PingIP {

 public static void runSystemCommand(String command) {

    try {
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader inputStream = new BufferedReader(
                new InputStreamReader(p.getInputStream()));

        String s = "";
        // reading output stream of the command
        while ((s = inputStream.readLine()) != null) {
            System.out.println(s);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {

    String ip = "google.com";
    runSystemCommand("ping " + ip);


  }
}

示例输出:

Pinging google.com [216.58.199.110] with 32 bytes of data:

Reply from 216.58.199.110: bytes=32 time=50ms TTL=53

Reply from 216.58.199.110: bytes=32 time=50ms TTL=53

Reply from 216.58.199.110: bytes=32 time=50ms TTL=53

Reply from 216.58.199.110: bytes=32 time=50ms TTL=53

Ping statistics for 216.58.199.110:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:
    Minimum = 50ms, Maximum = 50ms, Average = 50ms

我想知道如何获得平均ping并如何实时刷新平均ping?

1 个答案:

答案 0 :(得分:0)

此代码获取输出中Average的出现的索引,并从那里解析它以获取数字

    String test ="Approximate round trip times in milli-seconds: Minimum = 50ms, Maximum = 50ms, Average = 50ms";
    boolean done = false;
    int i = test.indexOf("Average");
    int average = 0;
    StringBuilder builder = new StringBuilder();
    while (!done)
    {
        char c = test.charAt(i);
        if(isNumber(c))
        {
            builder.append(c);
        }
        if(c == 'm')
        {
            done=true;
            average = Integer.valueOf(builder.toString());
        }
        i++;
    }
    System.out.println(average); 

和方法isNumber

static boolean isNumber(char c)
{
    return c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9'||c=='0';
}