개발/백

[JAVA/JSP]정확한 클라이언트 IP 주소 가져오기, request.getRemoteAddr() 해결 방법

다당근 2021. 11. 5. 15:24

 

[JAVA/JSP] request.getRemoteAddr() 로 정확한 IP 가 추출되지 않을 때 해결 방법, 정확한 클라이언트 IP 주소 가져오기

 

 

 

사용자 IP를 가져올때 보통 request.getRemoteAddr(); 을 사용해 가지고 오게 된다.

그러나 중간에 Load balancers 나 Procxy server 등이 개입되면서, request.getRemoteAddr() 함수로 IP 를 얻을 경우 다른 아이피가 나오게 된다. 

 

이러한 문제를 해결하기 위해 등장한 것이 X-Forwarded-For 헤더이다. X-Forwarded-For 헤더에서 IP를 추출하면 정확한 IP를 얻을 수 있다. 그러나 X-Forwarded-For 헤더 외 WL-Proxy-Client-IPProxy-Client-IP 와 같은 다른 헤더를 사용할 수 있기 때문에, 다음과 같이 IP를 구해주어야 한다.

 

JAVA

 

public static String getClientIP(HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    logger.info("> X-FORWARDED-FOR : " + ip);

    if (ip == null) {
        ip = request.getHeader("Proxy-Client-IP");
        logger.info("> Proxy-Client-IP : " + ip);
    }
    if (ip == null) {
        ip = request.getHeader("WL-Proxy-Client-IP");
        logger.info(">  WL-Proxy-Client-IP : " + ip);
    }
    if (ip == null) {
        ip = request.getHeader("HTTP_CLIENT_IP");
        logger.info("> HTTP_CLIENT_IP : " + ip);
    }
    if (ip == null) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        logger.info("> HTTP_X_FORWARDED_FOR : " + ip);
    }
    if (ip == null) {
        ip = request.getRemoteAddr();
        logger.info("> getRemoteAddr : "+ip);
    }
    logger.info("> Result : IP Address : "+ip);

    return ip;
}

 

 

JSP

다를 것 없이 선언문 안에서 사용하면 된다.

선언문이 뭔지 모를때 -> 참고

 

<%!
	public String getClientIP(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		System.out.println("> X-FORWARDED-FOR : " + ip);

		if (ip == null) {
			ip = request.getHeader("Proxy-Client-IP");
			System.out.println("> Proxy-Client-IP : " + ip);
		}
		if (ip == null) {
			ip = request.getHeader("WL-Proxy-Client-IP");
			System.out.println(">  WL-Proxy-Client-IP : " + ip);
		}
		if (ip == null) {
			ip = request.getHeader("HTTP_CLIENT_IP");
			System.out.println("> HTTP_CLIENT_IP : " + ip);
		}
		if (ip == null) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			System.out.println("> HTTP_X_FORWARDED_FOR : " + ip);
		}
		if (ip == null) {
			ip = request.getRemoteAddr();
			System.out.println("> getRemoteAddr : "+ip);
		}
		System.out.println("> Result : IP Address : "+ip);

		return ip;
	}
%>

 


출처

https://nine01223.tistory.com/302