在很多应用下都可能有需要将用户的真实IP记录下来,这时就要获得用户的真实IP地址,在JSP里,获取客户端的IP地址的方法是:request.getRemoteAddr(),这种方法在大部分情况下都是有效的。但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了
获得客户端真实IP地址
public String getIpAddr(HttpServletRequestrequest) {
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;
}
如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,取X-Forwarded-For中第一个非unknown的有效IP字符串
http://shanekwok.iteye.com/blog/150992