我正在尝试找出本地计算机当前正在使用哪个网络接口。我可以使用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如您所见,列出了两个接口。我的电脑目前用来连接互联网的是高通Atheros适配器。我可以只测试接口名称,看看它是否是Qualcomm适配器,但只有在我使用另一个Qualcomm适配器建立以太网连接之前,这才能起作用。
我在超级用户上看到一个similar question,它根据度量确定路由。
在Java中有没有一种干净的方法可以做到这一点呢?
发布于 2019-02-01 06:38:07
我找到了一个简洁的小方法来做到这一点:
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;
}正如您所看到的,我只是遍历网络接口并检查每个接口,以查看本地主机是否绑定到它。到目前为止,我还没有遇到这种方法的任何问题。
https://stackoverflow.com/questions/54470250
复制相似问题