InetAddress类中的isReachable问题

cod*_*rix 10 java networking icmp

作为一项任务,我必须在局域网上找到所有活着的计算机.我正在使用类的isReachable功能InetAddress.但问题是没有任何东西可以显示给我.所以我试图isReachable使用谷歌的IP,但仍然无法访问.

这是代码:

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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是: Unreachable

Ara*_*ram 5

以下是有关为什么isReachable()可能无法始终按预期工作的一些详细信息

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

正确的方法是使用ICMP协议.我认为这就是ping使用的内容.这是一个让你入门的例子.

  • javaranch 链接包含错误。isReachable() 不需要回声设备实际运行。它将连接拒绝解释为成功。 (2认同)