Java中使用HttpRequest擷取使用者真實IP地址

來源:互聯網
上載者:User

標籤:ret   vax   turn   字串   tps   nbsp   let   get   length   

 1 import javax.servlet.http.HttpServletRequest;   2    3 /**  4  * 自訂訪問對象工具類  5  *   6  * 擷取對象的IP地址等資訊  7  * @author X-rapido  8  *  9  */  10 public class CusAccessObjectUtil {  11   12     /** 13      * 擷取使用者真實IP地址,不使用request.getRemoteAddr();的原因是有可能使用者使用了代理軟體方式避免真實IP地址, 14 *  16      * 可是,如果通過了多級反向 Proxy的話,X-Forwarded-For的值並不止一個,而是一串IP值,究竟哪個才是真正的使用者端的真實IP呢? 17      * 答案是取X-Forwarded-For中第一個非unknown的有效IP字串。 18      *  19      * 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, 20      * 192.168.1.100 21      *  22      * 使用者真實IP為: 192.168.1.110 23      *  24      * @param request 25      * @return 26      */  27     public static String getIpAddress(HttpServletRequest request) {  28         String ip = request.getHeader("x-forwarded-for");  29         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  30             ip = request.getHeader("Proxy-Client-IP");  31         }  32         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  33             ip = request.getHeader("WL-Proxy-Client-IP");  34         }  35         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  36             ip = request.getHeader("HTTP_CLIENT_IP");  37         }  38         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  39             ip = request.getHeader("HTTP_X_FORWARDED_FOR");  40         }  41         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  42             ip = request.getRemoteAddr();  43         }  44         return ip;  45     }  46       47 }  

 

Java中使用HttpRequest擷取使用者真實IP地址

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.