본문 바로가기

Back-End/JAVA

[JAVA] 스프링 IP 주소 가져오기

~ 목차 ~

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api")
public class IpController {

    @GetMapping("/client-ip")
    public String getClientIp(HttpServletRequest request) {
        return getClientIpAddr(request);
    }

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

 

코드는 다음과 같은 순서로 헤더를 검사

  1. X-Forwarded-For
  2. Proxy-Client-IP
  3. WL-Proxy-Client-IP
  4. HTTP_CLIENT_IP
  5. HTTP_X_FORWARDED_FOR
  6. 기본적으로 request.getRemoteAddr()

이 메서드는 클라이언트의 실제 IP 주소를 얻기 위해 각 헤더를 차례대로 확인하며, 모든 헤더에 유효한 값이 없을 경우 request.getRemoteAddr()를 반환

 

Spring 환경에서 이 메서드를 사용할 경우, HttpServletRequest 객체를 주입받아 동일하게 사용할 수 있다.

 

이렇게 작성된 컨트롤러를 통해 /api/client-ip 엔드포인트에 접근하면 클라이언트의 IP 주소를 반환받을 수 있다.

 

주의 사항

  • 보안: 이 메서드는 신뢰할 수 없는 클라이언트가 HTTP 헤더를 조작할 수 있다는 점을 고려해야 한다. 따라서 민감한 보안 결정을 내릴 때는 IP 주소를 신뢰하지 않는 것이 좋다.
  • 프록시 설정: 여러 프록시 서버를 경유할 경우 X-Forwarded-For 헤더에 여러 개의 IP 주소가 포함될 수 있습니다. 이 경우 첫 번째 IP 주소가 원래 클라이언트의 IP 주소일 가능성이 큼.

Spring Boot 애플리케이션에서도 동일한 코드를 사용하여 클라이언트의 IP 주소를 얻을 수 있습니다.

728x90