1、问题:之前使用InetAddress.getLocalHost().getHostAddress()时,在开发机测试可以得到192.168.0.18这样的IP。但部署到linux服务器以后,

这个值却变成了127.0.0.1,如何得到真正的IP地址?

2、方案:

public static InetAddress getCurrentIp() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
Enumeration<InetAddress> nias = ni.getInetAddresses();
while (nias.hasMoreElements()) {
InetAddress ia = (InetAddress) nias.nextElement();
if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
return ia;
}
}
}
} catch (SocketException e) {
}
return null;
}
05-11 17:45