【问题标题】:Determine which NetworkInterface is currently being used确定当前正在使用哪个 NetworkInterface
【发布时间】:2019-02-01 06:38:07
【问题描述】:

我试图找出本地机器当前正在使用哪个网络接口。我可以使用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 适配器。我可以只测试接口名称以查看它是否是 Qualcomm 适配器,但这只有在我使用另一个 Qualcomm 适配器建立以太网连接之前才有效。

我在 Superuser 上看到了一个 similar question,它根据指标确定了路由。

在 Java 中有没有一种简洁的方法来做到这一点?

【问题讨论】:

    标签: java network-interface


    【解决方案1】:

    我找到了一个巧妙的小方法:

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多