2017-02-27 58 views
0

我想找到可以用来加入特定的远程主机的网络接口,我写了这个代码:为什么我找不到可以连接到特定主机的界面?

public static void main(String[] args) throws IOException 
{ 
    InetAddress t = InetAddress.getByName("10.10.11.101"); 

    // generic "icmp/ping" test 
    System.out.println(t.isReachable(5000)); 

    // same thing but for each interface 
    final Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); 
    for(final NetworkInterface netint : Collections.list(nets)) 
    { 
     if(netint.isUp() && !netint.isLoopback()) 
     { 
      System.out.println(t.isReachable(netint, 0, 5000) + " - " + netint); 
     } 
    } 
} 

结果是:

true 
false - name:eth4 (Intel(R) 82579LM Gigabit Network Connection) 
false - name:eth5 (VirtualBox Host-Only Ethernet Adapter) 
false - name:net6 (Carte Microsoft 6to4) 

正如你所看到的,通用的isReachable告诉我可以到达指定的主机,但由于未知原因,在每个接口上尝试这样做时,不会返回单个匹配。这很奇怪(在这种情况下,这应该是必须返回true的eth4)。

这是一个错误?我如何执行此任务(即使使用库)?

谢谢。

+0

也许在服务器端有一个“技巧”,所以它不会让你经常ping。这是我想到的唯一的事情。尝试从cmd使用ping,因为我已经阅读了这个协议,我没有很好地实现Java。 – JAAAY

+0

这似乎并不是这样,如果我禁用第一个isReachable测试循环仍然失败。 –

回答

0

好了,所以我试图另辟蹊径,找到界面,这里是如何我都做到了:

public static void main(String[] args) throws IOException 
{ 
    final InetAddress addr = InetAddress.getByName("10.10.11.8"); 
    final Socket s = new Socket(addr, 80); 

    System.out.println(searchInterface(s.getLocalAddress().getHostAddress())); 
} 

public static NetworkInterface searchInterface(final String interf) 
{ 
    try 
    { 
     final Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); 
     for(final NetworkInterface netint : Collections.list(nets)) 
     { 
      if(netint.isUp()) 
      { 
       final Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); 
       for(final InetAddress inetAddress : Collections.list(inetAddresses)) 
       { 
        if(inetAddress.getHostAddress().equals(interf)) 
        { 
         return netint; 
        } 
       } 
      } 
     } 
    } 
    catch(final SocketException e) 
    { 
    } 

    return null; 
} 

这是不是最好的方式做到这一点,因为你必须知道一个有效的开放端口在远程主机上,但对于我的问题,这仍然有效。

相关问题