overview
아무 생각없이 ip 를 가져와 보고 싶었다. 클라이언트 ip 를 가져오게 되면 좀 괞찬은 프로젝트를 할 것 같아서 ..
- 필터 구축
- 필터 등록
문서
https://khrdev.tistory.com/entry/Java%EB%A1%9C-Client-IP-%EC%B0%BE%EB%8A%94-%EB%B0%A9%EB%B2%95
Java로 Client IP 찾는 방법
Java로 개발을 하다 보면 로그인 이력을 남기거나 하는 상황에 Client IP를 데이터베이스에 Insert 하는 로직을 만들어야 하는 경우가 생길 수 있다.. 크게 2가지의 방법이 존재하는데 하나하나 설명
khrdev.tistory.com
https://developer.mozilla.org/ko/docs/Web/HTTP/Headers/X-Forwarded-For
X-Forwarded-For - HTTP | MDN
X-Forwarded-For (XFF) 헤더는 HTTP 프록시나 로드 밸런서를 통해 웹 서버에 접속하는 클라이언트의 원 IP 주소를 식별하는 사실상의 표준 헤더다. 클라이언트와 서버 중간에서 트래픽이 프록시나 로드
developer.mozilla.org
1. 필터 구축
솔직히 왠만하게 ip 라고만 쳐도 똑같은 코드들이기 때문에 ㅎㅎ.. 크게 의미는 없을 것 같다.
실질적인 ip 를 가져오는 메서드는 HttpServletRequest 의 getRomote 라고 한다.
HttpServletRequest httpRequest = (HttpServletRequest) request;
String ipAddress = httpRequest.getRemoteAddr(); // 클라이언트의 IP 주소 가져오기
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;
@Slf4j
@Component
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("filter 시작");
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Locale locale = request.getLocale();
String country = locale.getCountry();
log.info("지역 : {}" , country);
log.info("아이피 : {}" , getClientIp((HttpServletRequest) request));
chain.doFilter(request, response);
}
@Override
public void destroy() {
Filter.super.destroy();
}
public static String getClientIp(HttpServletRequest request) throws UnknownHostException {
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.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-RealIP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("REMOTE_ADDR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if(ip.equals("0:0:0:0:0:0:0:1") || ip.equals("127.0.0.1"))
{
InetAddress address = InetAddress.getLocalHost();
ip = address.getHostName() + "/" + address.getHostAddress();
}
return ip;
}
}
2. 필터 등록
필터를 등록 시키자
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class Config implements WebMvcConfigurer {
@Bean
public FilterRegistrationBean<MyFilter> methodFilterRegistrationBean() {
FilterRegistrationBean<MyFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new MyFilter());
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
}
3. 결과
음.. 그저 그렇다 ㅎ..
지역 : KR
아이피 : BOOK-..../아이피가 나옴
4. x-Forwarded-For
X-Forwarded-For (XFF) 헤더는 HTTP 프록시나 로드 밸런서를 통해 웹 서버에 접속하는 클라이언트의 원 IP 주소를 식별하는 사실상의 표준 헤더다. 클라이언트와 서버 중간에서 트래픽이 프록시나 로드 밸런서를 거치면, 서버 접근 로그에는 프록시나 로드 밸런서의 IP 주소만을 담고 있다. 클라이언트의 원 IP 주소를 보기위해 X-Forwarded-For 요청 헤더가 사용된다.
이 헤더는 디버깅, 통계, 그리고 위치 종속적인 컨텐츠를 위해 사용되고, 클라이언트의 IP 주소 등과 같은 민감한 개인정보를 노출시킨다. 그러므로 이 헤더를 사용할 때에는 사용자의 프라이버시를 주의해야 한다.
이 헤더의 표준화된 버전은 HTTP Forwarded 헤더다.
X-Forwarded-For 은 이메일 메시지가 다른 계정으로부터 포워딩되었음을 나타내는 이메일 헤더이기도 하다.
'SpringBoot' 카테고리의 다른 글
Springboot - @ResponseBody , @RequestBody (0) | 2024.02.06 |
---|---|
Springboot - RestTemplate , HttpHeaders , MultiValueMap , HttpEntity , URI , UriComponentsBuilder (1) | 2024.02.06 |
Springboot - @JsonNaming , @JsonProperty json 형식에 코딩 컨벤션의 스네이크 케이스를 카멜 노이션으로 변경하기 (0) | 2024.02.06 |
Springboot - OAuth 2.0(Open Authorization) 인증 방식의 이해 (1) | 2024.02.06 |
Springboot - Gmail의 STMP서버활용 이메일 전송 (0) | 2024.02.06 |