我开始深入研究通过 Java 获取 IP 地址。我知道一台机器可以通过不同的网络接口(interface)拥有不同的 IP,因此我对我发现的一些示例代码有些困惑,这些代码似乎返回“首选”IP 地址(按 Windows 7 命令行 ipconfig/all 首选)。
当我在本地计算机上运行以下代码时,返回 26 个 NetworkInterface 对象,其中一些对象具有多个 InetAddress 对象(包括“首选”对象):
Enumeration<NetworkInterface> eNI = null;
NetworkInterface ni = null;
Enumeration<InetAddress> eIA = null;
InetAddress ia = null;
try {
eNI = NetworkInterface.getNetworkInterfaces();
} catch (Exception e) {
}
while (eNI.hasMoreElements()) {
ni = eNI.nextElement();
System.out.println("NtwkIntfc name: " + ni.getName());
System.out.println("NtwkIntfc disp name: " + ni.getDisplayName());
try {
System.out.println("NtwkIntfc hardware addr: " + Hex.encodeHexString(ni.getHardwareAddress()));
} catch (Exception e) {
}
eIA = ni.getInetAddresses();
while (eIA.hasMoreElements()) {
ia = eIA.nextElement();
System.out.println("InetAddress host address: " + ia.getHostAddress());
System.out.println("InetAddress host name: " + ia.getHostName());
}
}
然而,这个简单得多的代码只是返回“首选”IPv4 地址:
try {
InetAddress thisIp = InetAddress.getLocalHost();
System.out.println("IP:" + thisIp.getHostAddress());
} catch (Exception e) {
e.printStackTrace();
}
我似乎找不到将其标识为“Preferred”的 NetworkInterface(以及其中的 InetAddress)属性/方法,所以我想知道类方法 InetAddress.getLocalHost() 是如何做到的?此外,此首选 IP 是标准网络概念还是某种类型的 Windows 特定概念?
谢谢。
最佳答案
查看网络设置中的指标。另请参阅 Windows 7 命令行下的“路由打印”。我认为指标越低,适配器就越“受青睐”。
关于java - InetAddress 类 getLocalHost() 如何返回 "Preferred"IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14817483/