下面的代碼片段只返回一個單一的InetAddress與我的主機名和環回地址127.0.1.1:InetAddress.getAllByName()不能像廣告一樣工作?
InetAddress[] allAddresses = InetAddress.getAllByName(host);
assert allAddresses.length == 1;
assert allAddresses[0].isLoopbackAddress();
不過,我能找到我的非環回網絡,像這樣:
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
for (Enumeration<NetworkInterface> e = networkInterfaces; e.hasMoreElements();) {
NetworkInterface networkInterface = e.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
for (Enumeration<InetAddress> eAddresses = inetAddresses; eAddresses.hasMoreElements();) {
InetAddress address = eAddresses.nextElement();
if (!address.isLoopbackAddress()) {
return address;
}
}
}
另外,我可以使用nslookup將我的主機名解析爲非回送IP。
InetAddress.getAllByName()聲明「給定主機的名稱,根據系統上配置的名稱服務返回其IP地址的數組。我是否缺少配置步驟?
** assert allAddresses.length == 1; **你爲什麼要這樣做? – 2011-06-12 17:09:11
只是爲了說明getAllByName()只返回長度爲1的數組。 – Damon 2011-06-12 17:13:04