如何运行PING命令并获取ping主机摘要?

Sal*_*aza 6 java command-line ping

嗨我需要PING使用Java代码执行命令并获取ping主机的摘要.怎么用Java做?

Hem*_*lia 15

作为指定的viruspatel你可以使用 Runtime.exec()

以下是它的一个例子

class pingTest {

    public static void main(String[] args) {
        String ip = "127.0.0.1";
        String pingResult = "";

        String pingCmd = "ping " + ip;
        try {
            Runtime r = Runtime.getRuntime();
            Process p = r.exec(pingCmd);

            BufferedReader in = new BufferedReader(new
            InputStreamReader(p.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                pingResult += inputLine;
            }
            in.close();

        } catch (IOException e) {
            System.out.println(e);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

产量

Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms
Run Code Online (Sandbox Code Playgroud)

请参阅http://www.velocityreviews.com/forums/t146589-ping-class-java.html


Dar*_*usz 5

InetAddress类有一个使用 ECMP Echo Request(又名 ping)来确定主机可用性的方法。

String ipAddress = "192.168.1.10";
InetAddress inet = InetAddress.getByName(ipAddress);
boolean reachable = inet.isReachable(5000);
Run Code Online (Sandbox Code Playgroud)

如果上述reachable变量为 true,则表示主机已在给定时间内(以毫秒为单位)正确回复 ECMP Echo Reply(又名 pong)。

注意:并非所有实现都必须使用 ping。该文件指出

如果可以获得权限,典型的实现将使用 ICMP ECHO REQUEST,否则它将尝试在目标主机的端口 7 (Echo) 上建立 TCP 连接。

因此,该方法可用于检查主机可用性,但不能普遍用于检查基于 ping 的检查。