为什么我找不到可以到达特定主机的接口?

Why can't I find the interface that can reach a specific host?

我想找到可用于加入特定远程主机的网络接口,我写了这段代码:

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 告诉我可以到达指定的主机,但由于未知原因,当尝试在每个接口上一个接一个地这样做时 return 没有一个匹配项。这很奇怪(在这种情况下,这应该是必须 return true 的 eth4)。

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

谢谢。

好的,所以我尝试了另一种方法来找到接口,这是我的做法:

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;
}

这不是最好的方法,因为您必须知道远程主机上的有效开放端口,但对于我的问题,这仍然有效。