java - 如何从网络接口获取 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");
}
解决方案
可能有更直接的方法,但如果您只是在寻找连接到互联网的接口,您可以使用一个简单的技巧,它不涉及读取路由表 - 只需创建一个套接字,将其连接到一个地址存在于互联网上,然后获取该套接字的本地地址。最好使用 UDP 套接字,因为它connect
不做任何实际的 IO:
DatagramSocket s = new DatagramSocket();
s.connect(InetAddress.getByName("1.1.1.1"), 53);
System.out.println(s.getLocalAddress());
操作系统将使用路由表将套接字绑定到用于出站连接的适当接口。获得 IP 地址后,您可以找到具有该 IP 地址的接口。
推荐阅读
- elasticsearch - 如何通过 td-agent 将 haproxy 日志发送到 fluentd?
- django - 我无法在 NFS 中写入文件名中有一些中文字符的文件
- c# - 如何停止对我的查询字符串进行 Refit 编码?
- reactjs - 当 redux 存储发生更改时,组件不会重新渲染
- c++ - 如何捕获为 lamda 表达式生成的函子的地址?
- apache-spark - 如何在条件语句中停止 Spark 解析 UDF 列
- django - Django授予外键对象权限
- angular - 在视图中使用简单的 get 方法成本高吗?
- python - 如何在 webdriver 上修复 NoSuchElementException
- kubernetes - 收到此错误!与服务器 localhost:8080 的连接被拒绝 - 您是否指定了正确的主机或端口?