獲取請求來源的IP地址


/** 
 * 獲取請求者的IP
 * 獲取用戶真實IP地址,不使用request.getRemoteAddr()的原因是有可能用戶使用了代理軟件方式避免真實IP地址, 
 * 可是,如果通過了多級反向代理的話,X-Forwarded-For的值並不止一個,而是一串IP值 
 * @return ip
 */
public static String getRealIp(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for"); 
    System.out.println("x-forwarded-for ip: " + ip);
    if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {  
        // 多次反向代理后會有多個ip值,第一個ip才是真實ip
        if( ip.indexOf(",")!=-1 ){
            ip = ip.split(",")[0];
        }
    }  
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = request.getHeader("Proxy-Client-IP");  
        System.out.println("Proxy-Client-IP ip: " + ip);
    }  
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = request.getHeader("WL-Proxy-Client-IP");  
        System.out.println("WL-Proxy-Client-IP ip: " + ip);
    }  
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = request.getHeader("HTTP_CLIENT_IP");  
        System.out.println("HTTP_CLIENT_IP ip: " + ip);
    }  
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
    }  
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = request.getHeader("X-Real-IP");  
        System.out.println("X-Real-IP ip: " + ip);
    }  
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = request.getRemoteAddr();  
        System.out.println("getRemoteAddr ip: " + ip);
    } 
    System.out.println("獲取客戶端ip: " + ip);
    return ip;  
}

 

/**
 * 獲取IP地址
 * @param request
 * @return
 */
public static String getRealIp(HttpServletRequest request) {
    String ip = request.getHeader("X-Real-IP");
    if (!StringUtils.isEmpty(ip) && !"unknow".equalsIgnoreCase(ip)) {
    } else {
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmpty(ip) && !"unknow".equalsIgnoreCase(ip)) {
            int index = ip.indexOf(',');
            if (index == -1) {
                ip = ip.substring(0, index);
            }
        } else {
            ip = request.getRemoteAddr();
        }
    }
    return ip;
}

 


免責聲明!

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



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