在web容器中,一般我们需要获取IP都是通过request来取得。
现在没有HttpRequest,那么如何获取机器IP呢?
刚开始我们下面的代码来获取,发现在linu上取出来的IP都是127.0.0.1。这个可能和linux下的hosts文件的配置有关,可以参考:https://blog.youkuaiyun.com/bestcxx/article/details/51220538。而且在java的main方法里面跑代码,也会有出现一会是127.0.0.1,一会是真正的IP的情况(但是这个好像只出现过一次,需要进一步的试验确认)
private static String getHostIp1() {
try {
InetAddress address = InetAddress.getLocalHost();
return address.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
return "";
}
}
既然这样不行,那就想其他的解决方法。于是有了下面的代码。参考:http://www.jb51.net/article/75100.htm。
注意这里ip.isLoopbackAddress()的方法。查看文档发现这是对回送地址(可以百度查看什么是回送地址,我认为上面出现的127.0.0.1就是没有去用这个来判断,而且127.0.0.1本来就是一个回送地址,我们可以通过ping 127.0.0.1来判断http是否正确安装,还是网络原因导致ping不通)的判断
public static String getHostIp() {
String sIP = "";
InetAddress ip = null;
try {
boolean bFindIP = false;
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
if (bFindIP)
break;
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
ip = ips.nextElement();
if (!ip.isLoopbackAddress()
&& ip.getHostAddress().matches("(\\d{1,3}\\.){3}\\d{1,3}")) {
bFindIP = true;
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (null != ip)
sIP = ip.getHostAddress();
return sIP;
}