如何 ping IP 地址

2022-08-31 11:59:13

我正在使用这部分代码在java中ping一个IP地址,但只有ping localhost是成功的,对于其他主机,程序说主机无法访问。我禁用了防火墙,但仍然遇到此问题

public static void main(String[] args) throws UnknownHostException, IOException {
    String ipAddress = "127.0.0.1";
    InetAddress inet = InetAddress.getByName(ipAddress);

    System.out.println("Sending Ping Request to " + ipAddress);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");

    ipAddress = "173.194.32.38";
    inet = InetAddress.getByName(ipAddress);

    System.out.println("Sending Ping Request to " + ipAddress);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");
}

输出为:

将 Ping 请求发送到 127.0.0.1
主机是可访问的
将 Ping 请求发送到 173.194.32.38
主机无法访问


答案 1

InetAddress.isReachable()根据javadoc

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

选项 #1 (ICMP) 通常需要管理权限。(root)


答案 2

我认为这段代码会帮助你:

public class PingExample {
    public static void main(String[] args){
        try{
            InetAddress address = InetAddress.getByName("192.168.1.103");
            boolean reachable = address.isReachable(10000);

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