首页 > 解决方案 > 如何从网络接口获取 IP 配置

问题描述

我有一个从网络接口提取信息的 java 应用程序,我正在使用 NetworkInterface 类来遍历我计算机中的无数接口。“我已经安装了 virtualbox”,这会创建许多虚拟界面。但我需要从我的无线或以太网接口获取信息,因为它们是连接到网络的唯一选择。问题是我希望能够对所有这些接口进行排序并只获得相关的。你们建议什么方法?通过 NetworkInterface 集合搜索 eth0 或 wlan1。任何想法表示赞赏。这是在我的应用程序中处理网络接口的代码。

//displaying all network interface 
Enumeration<NetworkInterface> nets = null;
try {
   nets = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e3) {
    e3.printStackTrace();
}

for (NetworkInterface netint : Collections.list(nets)) {            
   displayInterfaceInformation(netint);
}

static void displayInterfaceInformation(NetworkInterface netint) throws SocketException { 
    Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
    System.out.printf(count + " Display name: %s\n", netint.getDisplayName());
    System.out.printf("Name: %s\n", netint.getName());
    for (InetAddress inetAddress : Collections.list(inetAddresses)) {           
        System.out.printf("InetAddress: %s\n", inetAddress);
    }
    System.out.println("\n");
}

标签: javanetworkingnetwork-programmingnetwork-interface

解决方案


可能有更直接的方法,但如果您只是在寻找连接到互联网的接口,您可以使用一个简单的技巧,它不涉及读取路由表 - 只需创建一个套接字,将其连接到一个地址存在于互联网上,然后获取该套接字的本地地址。最好使用 UDP 套接字,因为它connect不做任何实际的 IO:

DatagramSocket s = new DatagramSocket();
s.connect(InetAddress.getByName("1.1.1.1"), 53);
System.out.println(s.getLocalAddress());

操作系统将使用路由表将套接字绑定到用于出站连接的适当接口。获得 IP 地址后,您可以找到具有该 IP 地址的接口。


推荐阅读