InetAddress.getByName(host).isReachable(timeout)的最佳替代方案 [英] best Alternative for InetAddress.getByName(host).isReachable(timeout)

查看:2325
本文介绍了InetAddress.getByName(host).isReachable(timeout)的最佳替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to reach a host and have the following code

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

我可以从Windows ping的主机名,并且还有一个tracert它返回所有数据包。但java抛出异常Host is not exists ::;

The hostname I am able to ping from windows, and also did a tracert on it and it returns all the packets. But java throws out exception "Host does not exist::";

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

The Timeout value I experimented from giving 2000ms, to 5000ms. I tried 3000 as well. What is the cause of this problem I am not able to understand. I researched on the net and some say that InetAddress.getByName(host).isReachable(time) is not reliable and behaves according to the internal system.

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

What is the best alternative for this if this is true. Please suggest.

推荐答案

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

Either open a TCP Socket to a port you think is open (22 for Linux, 139 for Windows, etc.)

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;
    }
}

或使用一些黑客发送实际的ping。 (受到启发: http://www.inprose.com/en / content / icmp-ping-in-java

Or use some hack to send an actual ping. (inspired from here: 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;
    }
}

可以找到Android的相同hack 在其中

Same hack for Android can be found here:

这篇关于InetAddress.getByName(host).isReachable(timeout)的最佳替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆