Java如何实现ping?

问:如果使用Java语言实现ping效果,而不是只执行ping命令?
答:可以调用java.net.InetAddress#isReachable(int)去实现。

    @Test
    public void addition_isCorrect() throws IOException, InterruptedException {
        InetAddress address = InetAddress.getByName("10.10.1.1");
        int timeOut = 3000;
        int retry = 15;
        for (int i = 0; i < retry; i++) {
            if (address.isReachable(timeOut)) {
                System.out.println(i + " OK");
            } else {
                System.out.println(i + " LOSS");
            }
            Thread.sleep(1000);
        }
    }

发表回复

CAPTCHAis initialing...