1. 程式人生 > >JAVA 獲取請求 IP 用於白名單驗證

JAVA 獲取請求 IP 用於白名單驗證

 獲取IP 

public static String getIpAddress(ServletRequest request) {
        String ip = ((HttpServletRequest) request).getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ((HttpServletRequest) request).getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ((HttpServletRequest) request).getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ((HttpServletRequest) request).getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ((HttpServletRequest) request).getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

本地測試獲取到的ip為 0:0:0:0:0:0:0:1

檢視 C:\Windows\System32\drivers\etc\hosts  這個檔案

0:0:0:0:0:0:0:1是ipv6的表現形式,對應ipv4 127.0.0.1  localhost是個域名,而不是一個ip地址。之所以我們經常把localhost與127.0.0.1認為是同一個是因為我們使用的大多數電腦上都講localhost指向了127.0.0.1這個地址。 

最有效的解決方案 :改變請求的ip,不要使用localhost