獲取客戶端真實IP地址

在現在軟件開發中,獲取客戶端的ip地址是非常常見的操作。request爲我們提供request.getRemoteAddr()方法提供ip地址,但是由於我們在一般軟件開發中基本都會使用代理,此時用request.getRemoteAddr()獲取ip地址就是代理服務器的地址。當使用代理服務時候,需要從代理添加ip請求頭中獲取對應的ip。

public class IpUtil {
    /**
     * 獲取用戶真實IP地址,不使用request.getRemoteAddr()的原因是有可能用戶使用了代理軟件方式避免真實IP地址,
     *
     */
    public static String getClientIp(HttpServletRequest request) {
        //如果通過了多級反向代理的話,X-Forwarded-For的值並不止一個,而是一串IP值
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理後會有多個ip值,第一個ip纔是真實ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        //apache http做代理時一般會加上Proxy-Client-IP請求頭
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        //apache http做代理時,weblogic插件加上WL-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.getHeader("HTTP_CLIENT_IP");
        }
        //分代理服務器加的請求頭
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        //nginx代理一般會加上此請求頭
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        //當不使用代理獲取的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;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章