Java中的isReachable看起来并没有像预期的那样工作

前端之家收集整理的这篇文章主要介绍了Java中的isReachable看起来并没有像预期的那样工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在使用Clojure,但我可以阅读Java,所以这不是Clojure特定的问题.这甚至似乎都不适用于Java.

我正在尝试使用isReachable实现一些’ping’功能.我正在使用的代码是这样的:

(.isReachable (java.net.InetAddress/getByName "www.microsoft.com") 5000)

我的一位好朋友翻译成Java:

public class NetTest {
  public static void main (String[] args) throws Exception{
    String host = "acidrayne.net";
    InetAddress a = InetAddress.getByName(host);

    System.out.println(a.isReachable(10000));
  }
}

这两个都返回false.我想我一定是做错了,但谷歌的研究告诉我的不同之处.我很困惑!

最佳答案
更新以回应评论这是错误的:

使用Unix / Linux ??

http://bordet.blogspot.com/2006/07/icmp-and-inetaddressisreachable.html说:

Linux/Unix,instead,supports an ICMP “ping” system call. So the implementation of java.net.InetAddress.isReachable() first tries to perform the “ping” system call**; if this fails,it falls back trying to open a TCP socket on [sic – to] port 7,as in Windows.

It turns out that in Linux/Unix the ping system call requires root privileges,so most of the times java.net.InetAddress.isReachable() will fail,because many Java programs are not run as root,and because the target address unlikely has the echo service up and running. Too bad.

@EJP下面的评论表明关于echo服务的部分是错误的,错误错误

That’s not correct. isReachable returns true if it gets a ConnectException trying to connect to port 7,as that proves that the host is up and able to send RST segments.

在这些情况下,我使用WireShark,tcpdump(Windows上的WinDump)或snoop(Solaris)等数据包嗅探器来确认线路上发生了什么.

猜你在找的Java相关文章