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

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

问题描述

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

为什么 isReachable 返回 false?我可以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.否则,您将得到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) 此解决方案不是生产质量.它有点像黑客.如果谷歌关闭,或者您的互联网暂时变慢,或者即使您的权限/系统设置有一些有趣的地方,如果可能返回假阴性(即,即使输入地址可访问,它也可能失败).2) isReachable 失败是一个突出的问题.再次 - 有几个在线资源表明在撰写本文时没有完美"的方式来执行此操作,这是由于 JVM 尝试访问主机的方式 - 我猜这是一个本质上特定于平台的任务,虽然很简单, 尚未被 JVM 充分抽象.

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

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