HttpServletRequest获取真实IP地址(无视代理)详解

HttpServletRequest获取IP地址(无代理)

//获取发送请求的客户端主机的IP
request.getRemoteAddr //返回127.0.0.1

HttpServletRequest获取真实IP地址(代理)

如果通过Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了。如果使用了反向代理软件,用 request.getRemoteAddr()方法获取的IP地址是代理的IP,而并不是客户端的真实IP。获取真实IP有如下2种方法:

//获取真实IP一
public String getRemortIP(HttpServletRequest request) {
  if (request.getHeader("x-forwarded-for") == null) {
   return request.getRemoteAddr();
  }
  return request.getHeader("x-forwarded-for");
}
//获取真实IP二
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;
}

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。