現(xiàn)象:在進(jìn)行數(shù)據(jù)測試時(shí),無意發(fā)現(xiàn)某臺(tái)機(jī)器返回的IP不正確,其返回的為127.0.0.1
。但其它機(jī)器均為正常。
該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),是因?yàn)闆]有設(shè)置主機(jī)的hostname導(dǎo)致的。其解析的邏輯是根據(jù)localHostName
來獲取的,而localHostName
在虛擬機(jī)里面默認(rèn)為localhost.localdomain
,而localhost.localdomain
對(duì)應(yīng)的則默認(rèn)為127.0.0.1,
更改機(jī)器的hostname即可,其更改hostname方法如下:
hostnamectl set-hostname xxx
可以通過以下獲取所有的IP(針對(duì)多網(wǎng)卡),并且對(duì)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;
}