无论IP地址是什么,isReachable始终返回true [英] isReachable always returning true regardless of what the IP address is

查看:447
本文介绍了无论IP地址是什么,isReachable始终返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在使用isReachable来"ping"我的Java代码中的地址.这个代码块是每个人似乎都在使用的代码:

So I have been using isReachable to "ping" an address in my java code. This block of code is what everyone seems to use:

    try
    {
    InetAddress address = InetAddress.getByName("172.16.2.0");
    // Try to reach the specified address within the timeout
    // periode. If during this periode the address cannot be
    // reach then the method returns false.
    boolean reachable = address.isReachable(10000);
    System.out.println("Is host reachable? " + reachable);
    } catch (Exception e)
    {
    e.printStackTrace();
    }

我的问题是,无论我用什么IP地址,它总是返回true.即使我将其更改为空字符串.有什么想法吗?

My issue is that no matter what I use for my IP address it always returns true. Even if I change it to empty string. Any ideas why?

推荐答案

一种通过java.net.InetAddress.isReachable()方法检查某些地址是否可访问的方法. 这些方法的实现是本机的,并尝试尽其所能来"ping" InetAddress表示的地址.

A way to check if some address is reachable, via java.net.InetAddress.isReachable() methods. The implementation of these methods goes native and tries to do its best to "ping" the address represented by the InetAddress.

令人惊讶的是,Windows和java.net.InetAddress.isReachable()的Linux/Unix实现之间存在许多差异.

Surprisingly, there are many differences between the Windows and the Linux/Unix implementation of java.net.InetAddress.isReachable().

Windows看起来似乎很奇怪,但它并不正式支持ICMP"ping"系统调用.因此,Java SE 5实现会尝试在端口7(回显服务)上打开TCP套接字,并希望获得某种答复.

Windows, as strange as it seems, does not officially support an ICMP "ping" system call. The Java SE 5 implementation hence tries to open a TCP socket on port 7 (the echo service) and hopes to get some sort of reply.

相反,Linux/Unix支持ICMP"ping"系统调用.因此,java.net.InetAddress.isReachable()的实现首先尝试执行"ping"系统调用.如果失败,则回退尝试在Windows 7上打开端口7上的TCP套接字.

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 port 7, as in Windows.

事实证明,在Linux/Unix中,ping系统调用需要root特权,因此大多数时候java.net.InetAddress.isReachable()都会失败,因为许多Java程序不是以root身份运行的.

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.

正确的方法是ICMP协议.这就是 ping 在内部使用的功能.建议参见

The correct approach is the ICMP protocol. This is what ping uses internally. It is recommended see THIS to gather knowledge and proceed.

FROM:: Simone Bordet的博客

这篇关于无论IP地址是什么,isReachable始终返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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