InetAddress.getByName(host).isReachable(timeout)的最佳替代方案

8 java host ping

我正在尝试访问主机并拥有以下代码

if(!InetAddress.getByName(host).isReachable(TIMEOUT)){
   throw new Exception("Host does not exist::"+ hostname);
 }
Run Code Online (Sandbox Code Playgroud)

我可以从Windows ping主机名,并在其上执行tracert并返回所有数据包.但java抛出异常"Host is not exists ::";

从实现2000ms到5000ms的超时值.我也试过3000.我无法理解这个问题的原因是什么.我在网上研究过,有人说InetAddress.getByName(host).isReachable(time)不可靠,并且根据内部系统行事.

如果这是真的,最好的选择是什么.请建议.

Shl*_*oim 14

打开TCP套接字到您认为打开的端口(Linux为22,Windows为139等)

public static boolean isReachableByTcp(String host, int port, int timeout) {
    try {
        Socket socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress(host, port);
        socket.connect(socketAddress, timeout);
        socket.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者使用一些hack来发送实际的ping.(灵感来自:http://www.inprose.com/en/content/icmp-ping-in-java)

public static boolean isReachableByPing(String host) {
    try{
        String cmd = "";

        if(System.getProperty("os.name").startsWith("Windows"))
            cmd = "cmd /C ping -n 1 " + host + " | find \"TTL\"";
        else
            cmd = "ping -c 1 " + host;

        Process myProcess = Runtime.getRuntime().exec(cmd);
        myProcess.waitFor();

        return myProcess.exitValue() == 0;
    } catch( Exception e ) {
        e.printStackTrace();
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

Android的相同hack可以在这里找到: