1. 程式人生 > >[轉]Java web 開發 獲取使用者ip

[轉]Java web 開發 獲取使用者ip

如果通過了多級反向代理的話,X-Forwarded-For的值並不止一個,而是一串IP值,那麼真正的使用者端的真實IP則是取X-Forwarded-For中第一個非unknown的有效IP字串。

public String getClientIpAddr(Request 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.getRemoteAddress();
        }
        return ip;
    }