简体   繁体   English

InetAddress类中的isReachable问题

[英]Problem with isReachable in InetAddress class

As an assignment I have to find all the alive computers on a LAN. 作为一项任务,我必须在局域网上找到所有活着的计算机。 For which I am using isReachable function of InetAddress class. 我正在使用的是InetAddress类的isReachable函数。 But problem is that nothing is shown reachable to me. 但问题是没有任何东西可以显示给我。 So I tried to have isReachable with Google's IP but still this is unreachable. 所以我尝试使用Google的IP进行isReachable ,但仍然无法访问。

Here is the code: 这是代码:

import java.net.*;

public class alive{
    public static void main(String args[]){
        try{
            InetAddress ia = InetAddress.getByAddress(new byte[]{(byte)209, (byte)85, (byte)153, (byte)104});
            boolean b = ia.isReachable(10000);
            if(b){
                System.out.println("Reachable");
            }
            else{
                System.out.println("Unrachable");
            }

        }catch(Exception e){
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Output is : Unreachable 输出是: Unreachable

Here are some details on why isReachable() might not always work as expected 以下是有关为什么isReachable()可能无法始终按预期工作的一些详细信息

  1. http://bordet.blogspot.com/2006/07/icmp-and-inetaddressisreachable.html http://bordet.blogspot.com/2006/07/icmp-and-inetaddressisreachable.html
  2. http://www.coderanch.com/t/206934/sockets/java/InetAdress-isReachable-Ping-Permissions http://www.coderanch.com/t/206934/sockets/java/InetAdress-isReachable-Ping-Permissions

The correct way for you is to use the ICMP protocol. 正确的方法是使用ICMP协议。 This is what ping uses internatlly, I believe. 我认为这就是ping使用的内容。 Here is an example that get you started. 这是一个让你入门的例子

Here is the code which is platform independent, but requires information about any open port on the other machine (which we have most of the time). 这是与平台无关的代码,但需要有关另一台机器上任何开放端口的信息(我们大多数时间都是这样)。

private static boolean isReachable(String addr, int openPort, int timeOutMillis) {
    // Any Open port on other machine
    // openPort =  22 - ssh, 80 or 443 - webserver, 25 - mailserver etc.
    try {
        try (Socket soc = new Socket()) {
            soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis);
        }
        return true;
    } catch (IOException ex) {
        return false;
    }
}

I found interesting solution. 我发现有趣的解决方案 If you can't run your aplication as root, you may set raw socket capability on java: 如果您无法以root用户身份运行应用程序,则可以在java上设置原始套接字功能:

sudo setcap cap_net_raw=ep /usr/lib/jvm/jdk/bin/java

And then ICMP protocol will be used istead of echo request on 7 TCP port. 然后将使用ICMP协议而不是7 TCP端口上的echo请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM