确定当前正在使用哪个 NetworkInterface

Determine which NetworkInterface is currently being used

我想弄清楚本地计算机当前正在使用哪个网络接口。我可以使用 NetworkInterface.getNetworkInterfaces() 获取我机器上安装的所有接口,但我无法确定计算机使用哪个接口访问互联网。

我尝试过滤掉非活动和环回接口,然后打印剩余的:

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
    NetworkInterface face = interfaces.nextElement();

    if (face.isLoopback() || !face.isUp()) {
        continue;
    }

    System.out.println(face.getDisplayName());
}

结果如下:

Qualcomm Atheros AR9485 802.11b/g/n WiFi Adapter
Microsoft ISATAP Adapter #5

如您所见,列出了两个接口。我的电脑目前用于连接互联网的是 Qualcomm Atheros 适配器。我可以只测试接口名称,看看它是否是高通适配器,但这只能在我使用另一个高通适配器建立以太网连接之前起作用。

我在 Superuser 上看到一个 similar question 根据度量确定路由。

在 Java 中是否有一种干净的方法可以做到这一点?

我找到了一个巧妙的小方法来做到这一点:

public static NetworkInterface getCurrentInterface() throws SocketException, UnknownHostException {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    InetAddress myAddr = InetAddress.getLocalHost();
    while (interfaces.hasMoreElements()) {
        NetworkInterface face = interfaces.nextElement();

        if (Collections.list(face.getInetAddresses()).contains(myAddr))
            return face;
    }
    return null;
}

如您所见,我只是遍历网络接口并检查每个接口以查看本地主机是否绑定到它。到目前为止,我对这种方法没有任何问题。