【request获取用户请求ip】
1:request.getRemoteAddr()
2:如果请求的客户端使用了nginx 等反向代理发送请求的时候:就不能获取到真是的ip地址了:如:将http://192.168.1.110:2046/ 的URL反向代理为http://www.xxx.com/ 的URL时,用request.getRemoteAddr() 方法获取的IP地址是:127.0.0.1 或 192.168.1.110 ,而并不是客户端的真实IP。
3:解决:
public
String getRemoteHost(javax.servlet.http.HttpServletRequest request){
String ip = request.getHeader(
"x-forwarded-for"
);
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.getRemoteAddr();
}
return
ip.equals(
"0:0:0:0:0:0:0:1"
)?
"127.0.0.1"
:ip;
}