InetAddress.getLocalHost().getHostAddress()可以獲取本機,某種情況下獲取的是127.0.0.1,讓人無語。
問題分析:
在linux環境中,在根目錄中etc 的hosts 文件中可以看到如下語句
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
這樣,當語句InetAddress.getLocalHost().getHostAddress()
搜索到本機名是沒有結果,就默認爲localhost,而localhost對應的IP已經指明爲 127.0.0.1,所以你獲取不到你預想的IP。
解決辦法:
1. 修改hosts文件,增加一行IP與計算機名的對應,比如:10.166.8.195 dev-fengkong-1 ,其中dev-fengkong-1是計算機名。
2. 改進獲取IP方法,如下。
改進後的獲取IP方法:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NetAddressUtil {
private static final Logger logger = LoggerFactory.getLogger(NetAddressUtil.class);
private static String netAddress = "";
public static String getLocalNetAddress() {
if (StringUtils.isNotBlank(netAddress)) {
return netAddress;
}
try {
InetAddress candidateAddress = null;
遍歷所有的網絡接口
for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
在所有的接口下再遍歷IP
for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
if (!inetAddr.isLoopbackAddress()) { 排除loopback類型地址
if (inetAddr.isSiteLocalAddress()) {
如果是site-local地址,就是它了
netAddress = inetAddr.getHostAddress();
return netAddress;
} else if (candidateAddress == null) {
site-local類型的地址未被發現,先記錄候選地址
candidateAddress = inetAddr;
}
}
}
}
if (candidateAddress != null) {
netAddress = candidateAddress.getHostAddress();
return netAddress;
}
如果沒有發現 non-loopback地址.只能用最次選的方案
InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
netAddress = jdkSuppliedAddress.getHostAddress();
return netAddress;
} catch (Exception e) {
logger.error("get local net address error:" + e.getMessage());
return netAddress;
}
}
public static void main(String[] args) {
System.out.println(getLocalNetAddress());
}
}
親測可用,謝謝!