現(xiàn)象:在進行數(shù)據(jù)測試時,無意發(fā)現(xiàn)某臺機器返回的IP不正確单起,其返回的為127.0.0.1
之剧。但其它機器均為正常够吩。
該IP是通過InetAddress.getLocalHost()
獲取IP地址,查看該方法見其注釋為:
* <p>If there is a security manager, its
* {@code checkConnect} method is called
* with the local host name and {@code -1}
* as its arguments to see if the operation is allowed.
* If the operation is not allowed, an InetAddress representing
* the loopback address is returned.
通過跟蹤源碼發(fā)現(xiàn)囤攀,是因為沒有設置主機的hostname導致的软免。其解析的邏輯是根據(jù)localHostName
來獲取的,而localHostName
在虛擬機里面默認為localhost.localdomain
焚挠,而localhost.localdomain
對應的則默認為127.0.0.1膏萧,
更改機器的hostname即可,其更改hostname方法如下:
hostnamectl set-hostname xxx
可以通過以下獲取所有的IP(針對多網(wǎng)卡)蝌衔,并且對IP6地址過濾:
public static List<String> getHostAddresses(Boolean filterIp6) {
List<String> result = new ArrayList<>();
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
continue;
}
Enumeration<InetAddress> address = networkInterface.getInetAddresses();
while (address.hasMoreElements()) {
InetAddress add = address.nextElement();
if (filterIp6 == null || filterIp6.booleanValue() == true) {
if (add.getHostAddress().contains(":")) {
continue;
}
}
result.add(add.getHostAddress());
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return result;
}