Java获取本地IP异常问题
获取本地IP往往只需要:InetAddress.getLocalHost().getHostAddress()就行了,但是今天在测试的时候发现这个方法并不怎么靠谱。服务器配置有问题导致无法通过主机名获取IP地址从而抛出了一个UnknowHostException。临时的程序解决办法是假设getLocalHost异常则用NetworkInterface方法获取IP:
public InetAddress getLocalHostLANAddress() throws UnknownHostException {
try {
InetAddress candidateAddress = null;
for (Enumeration<?> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
for (Enumeration<?> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
if (!inetAddr.isLoopbackAddress()) {
if (inetAddr.isSiteLocalAddress()) {
return inetAddr;
}
else if (candidateAddress == null) {
candidateAddress = inetAddr;
}
}
}
}
if (candidateAddress != null) {
return candidateAddress;
}
InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
if (jdkSuppliedAddress == null) {
throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
}
return jdkSuppliedAddress;
}
catch (Exception e) {
UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);
unknownHostException.initCause(e);
throw unknownHostException;
}
}
public InetAddress getLocalHost(){
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getLocalHost();
} catch (Exception e) {
try {
inetAddress = getLocalHostLANAddress();
} catch (UnknownHostException e1) {
ClientLogger.clog(e);
}
}
return inetAddress;
}