java 获取请求客户端的真实IP地址

用request.getRemoteAddr()
方法获取的IP地址是:127.0.0.1 或 192.168.0.66,而并不是客户端的真实IP。

经过代理以后,由于在客户端和服务之间增加了中间层,因此服务器无法直接拿到客户端的IP,服务器端应用也无法直接通过转发请求的地址返回给客户端。但是在转发请求的HTTP头信息中,增加了X-FORWARDED-FOR

信息用以跟踪原有的客户端IP地址和原来客户端请求的服务器地址。

 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;     
}

像移动网关一样,iisforward这个ISAPI过滤器也会对request对象进行再包装,附加一些WLS要用的头信息。这种情况下,直接用request.getRemoteAddr()是无法取到真正的客户IP的。

实际的iisforward附加头如下:

WL-Proxy-Client-IP=215.4.1.29
Proxy-Client-IP=215.4.1.29
X-Forwarded-For=215.4.1.29
WL-Proxy-Client-Keysize=
WL-Proxy-Client-Secretkeysize=
X-WebLogic-Request-ClusterInfo=true
X-WebLogic-KeepAliveSecs=30
X-WebLogic-Force-JVMID=-527489098
WL-Proxy-SSL=false

综上,正确作法如下:代码

public static String getIpAddr(HttpServletRequest request) {
     String ipAddress = null;
     //ipAddress = request.getRemoteAddr();
     ipAddress = request.getHeader("x-forwarded-for");
     if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getHeader("Proxy-Client-IP");
     }
     if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
         ipAddress = request.getHeader("WL-Proxy-Client-IP");
     }
     if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getRemoteAddr();
      if(ipAddress.equals("127.0.0.1")){
       //根据网卡取本机配置的IP
       InetAddress inet=null;
    try {
     inet = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
     e.printStackTrace();
    }
    ipAddress= inet.getHostAddress();
      }
       
     }

     //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
     if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
         if(ipAddress.indexOf(",")>0){
             ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
         }
     }
     return ipAddress;
}


你可能感兴趣的:(工具类)