Java如何ping主机?

从Java 1.5(Tiger)开始,java.net.InetAddress该类引入isReachable()了可用于ping或检查由所指定的地址InetAddress是否可访问的方法。

package org.nhooo.example.network;

import java.net.InetAddress;

public class PingExample {
    public static void main(String[] args) {
        try {
            InetAddress address = InetAddress.getByName("172.16.2.0");

            // 尝试在超时时间内到达指定的地址
            //期。如果在此期间该地址不能为
            // 到达则该方法返回false。
            boolean reachable = address.isReachable(10000);

            System.out.println("Is host reachable? " + reachable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}