在项目中需要获取客户端的真实IP地址,原本使用的是request.getRemoteAddr(),后来发布到服务器上时发现取到的值一直是127.0.0.1
原因是,在部署时用了nginx进行反向代理,
(小插曲:配nginx的时候一定要记得配 X-Real-IP和 X-Forwarded-For如下,不然还是取不到啊)
解决办法:
经过代理以后,由于在客户端和服务之间增加了中间层,因此服务器无法直接拿到客户端的IP,服务器端应用也无法直接通过转发请求的地址返回给客户端。但是在转发请求的HTTP头信息中,增加了 X-Real-IP和 X-Forwarded-For信息。即可获取。
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
String xip = request.getHeader("X-Real-IP");
if(ip != null && ip.length()!=0 && !ip.equalsIgnoreCase("unKnown")){
int index = ip.indexOf(",");
if(index != -1){
return ip.substring(0,index);
}else{
return ip;
}
}
ip = xip;
if(ip != null && ip.length()!=0 && !ip.equalsIgnoreCase("unKnown")){
return ip;
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
参考:http://dpn525.iteye.com/blog/1132318