当我可以ping IP地址时,为什么InetAddress.isReachable返回false? [英] Why does InetAddress.isReachable return false, when I can ping the IP address?

查看:571
本文介绍了当我可以ping IP地址时,为什么InetAddress.isReachable返回false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    InetAddress byName = InetAddress.getByName("173.39.161.140");
    System.out.println(byName);
    System.out.println(byName.isReachable(1000));

为什么 isReachable 返回?我可以ping IP。

Why does isReachable return false? I can ping the IP.

推荐答案

isReachable方法不值得使用在很多情况下我。您可以滚动到底部查看我的替代方案,只需测试您是否在线且能够解析外部主机(即google.com)...这通常似乎适用于* NIX机器。

The "isReachable" method has not been worthy of using for me in many cases. You can scroll to the bottom to see my alternative for simply testing if you're online and capable of resolving external hosts (i.e. google.com) ... Which generally seems to work on *NIX machines.

问题

有很多关于此事的喋喋不休:

There is alot of chatter about this :


  • 以下是其他类似问题:

  • Here are other, similar questions :

使用Java检测互联网连接

如何在Java中测试互联网的可用性?

甚至报道了同一事件的错误:

And even a reported bug on this same matter :

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4921816

第1部分:问题的可重复示例

请注意,在这种情况下,它会失败。

Note that in this case, it fails.

       //also, this fails for an invalid address, like "www.sjdosgoogle.com1234sd" 
       InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
      for (InetAddress address : addresses) {
        if (address.isReachable(10000))
        {   
           System.out.println("Connected "+ address);
        }
        else
        {
           System.out.println("Failed "+address);
        }
      }
          //output:*Failed www.google.com/74.125.227.114*

第2部分:黑客解决方法

作为替代方案,您可以这样做:

As an alternative, you can do this :

// in case of Linux change the 'n' to 'c'
    Process p1 = java.lang.Runtime.getRuntime().exec("ping -n 1 www.google.com");
    int returnVal = p1.waitFor();
    boolean reachable = (returnVal==0);

ping 的-c选项将允许ping只是试图达到服务器一次(而不是我们习惯在终端上使用的无限ping)。

The -c option of ping will allow ping to simply try to reach the server once(as opposed to the infinite ping which we're used to using at the terminal).

如果主机可以访问,这将返回 0 / strong>即可。否则,您将获得2作为返回值。

This will return 0 if the host is reachable. Otherwise, you will get "2" as a return value.

更简单 - 但当然它是特定于平台的。
使用此命令可能存在某些特权警告 - 但我发现它可以在我的机器上运行。

Much simpler - but of course it is platform specific. And there may be certain privilege caveats to using this command - but I find it works on my machines.

请注意:
1)此解决方案不是生产质量。它有点像黑客。如果google关闭,或者您的互联网暂时变慢,或者即使您的权限/系统设置中存在某些漏洞,也可能会返回漏报(即即使输入地址可以访问也可能失败)。
2)isReachable失败是一个突出的问题。再次 - 由于JVM尝试访问主机的方式,有几个在线资源表明在撰写本文时没有完美的方式这样做 - 我想这是一个本质上特定于平台的任务,尽管很简单,尚未被JVM充分抽象。

这篇关于当我可以ping IP地址时,为什么InetAddress.isReachable返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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