Java擷取請求用戶端的真實IP地址

來源:互聯網
上載者:User

 

轉自 http://blog.csdn.net/foamflower/archive/2009/10/29/4744862.aspx

 

像移動網關一樣,iisforward這個ISAPI過濾器也會對request對象進行再封裝,附加一些WLS要用的頭資訊。這種情況下,直接用request.getRemoteAddr()
是無法取到真正的客戶IP的。

實際的iisforward附加頭如下:

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

綜上,正確作法如下:

private String getIpAddr() {
     String ipAddress = null;
     //ipAddress = this.getRequest().getRemoteAddr();
     ipAddress = this.getRequest().getHeader("x-forwarded-for");
     if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = this.getRequest().getHeader("Proxy-Client-IP");
     }
     if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
         ipAddress = this.getRequest().getHeader("WL-Proxy-Client-IP");
     }
     if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = this.getRequest().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;
  }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.