method 1:
public String getRemortIP(HttpServletRequest request) {
if (request.getHeader("x-forwarded-for") == null) {
return request.getRemoteAddr();
}
return request.getHeader("x-forwarded-for");
}
method 2:
public String getIpAddr(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;
}
原因:
当我们访问index.jsp/时,其实并不是我们浏览器真正访问到了服务器上的index.jsp 文件,而是先由代理服务器去访问index.jsp
,代理服务器再将访问到的结果返回给我们的浏览器,因为是代理服务器去访问index.jsp的,所以index.jsp中通过
request.getRemoteAddr()的方法获取的IP实际上是代理服务器的地址,并不是客户端的IP地址。
注:
如果X-Forwarded-For的返回值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢?
那就取X-Forwarded-For中第一个非unknown的有效IP字符串。
reference:http://www.jb51.net/article/21272.htm
如果你在本地使用localhost或127.0.0.1地址来测试,那只能获取到127.0.0.1,而对于外网访问者,是一定可以获取得到他的真实IP的。 String realIP=request.getHeader("x-forwarded-for");
String ip = request.getRemoteAddr();
if(realIP==null||realIP.length()==0)
{out.println("真实IP:"+ip);
}else{out.println("真实IP:"+realIP);}