【request獲取用戶請求ip】


1:request.getRemoteAddr()

2:如果請求的客戶端使用了nginx 等反向代理發送請求的時候:就不能獲取到真是的ip地址了:如:將http://192.168.1.110:2046/ 的URL反向代理為http://www.xxx.com/ 的URL時,用request.getRemoteAddr() 方法獲取的IP地址是:127.0.0.1 或 192.168.1.110 ,而並不是客戶端的真實IP。

3:解決:

 

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM