java 獲取請求客戶端的真實IP地址

用request.getRemoteAddr() 
服務器

方法獲取的IP地址是:127.0.0.1 或 192.168.0.66,而並非客戶端的真實IP。 

通過代理之後,因爲在客戶端和服務之間增長了中間層,所以服務器沒法直接拿到客戶端的IP,服務器端應用也沒法直接經過轉發請求的地址返回給客戶端。可是在轉發請求的HTTP頭信息中,增長了X-FORWARDED-FOR 

信息用以跟蹤原有的客戶端IP地址和原來客戶端請求的服務器地址。
spa

 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
ip

綜上,正確做法以下:代碼get

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

相關文章
相關標籤/搜索