진이의 Developer Story

스프링에서 클라이언트IP 가져오기 본문

Java/Spring

스프링에서 클라이언트IP 가져오기

JIN3260 2018. 4. 30. 09:45

포워드IP의 경우 제대로 걸러지지 않는 경우가 있다.

헤더에서 구분하여 IP값을 받아오자.


public static String getClientIP() {

    HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();

    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.getHeader("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }

    // ipv6 (ipv4 127.0.0.1) localhost로 접속했을시
    if("0:0:0:0:0:0:0:1".equals(ip)){
        ip = "127.0.0.1";
    }
    
    return ip;

}

Comments