如何从网络接口获取 IP 配置

How Do I Get Ip Configuration From Network Interface

我有一个 java 应用程序可以从网络接口中提取信息,我正在使用 NetworkInterface class 来遍历我计算机中的无数接口。 "I have installed virtualbox" 这会创建许多虚拟接口。但我需要从我的无线或以太网接口获取信息,因为这些是连接到网络的唯一选项。问题是我希望能够对所有这些接口进行分类并只获得相关的。你们建议什么方法?通过 NetworkInteface 集合进行搜索以查找 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");
}

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

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

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