1. 程式人生 > >java獲取請求者IP地址

java獲取請求者IP地址



    public static String getIPAddress(HttpServletRequest request) {
        String ip = null;


        //X-Forwarded-For:Squid 服務代理
        String ipAddresses = request.getHeader("X-Forwarded-For");


        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP:apache 服務代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }


        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP:weblogic 服務代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }


        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP:有些代理伺服器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }


        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP:nginx服務代理
            ipAddresses = request.getHeader("X-Real-IP");
        }


        //有些網路通過多層代理,那麼獲取到的ip就會有多個,一般都是通過逗號(,)分割開來,並且第一個ip為客戶端的真實IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }


        //還是不能獲取到,最後再通過request.getRemoteAddr();獲取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }