Reputation: 999
I used to call HttpServletRequest.getRemoteAddr() to get client ip.
I'm wondering how can I get it via ServerWebExchange.
My best guess is:
serverWebExchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
Is it correct?
Upvotes: 5
Views: 10877
Reputation: 55
you can use org.springframework.http.server.reactive.ServerHttpRequest
,
String remoteAddress = serverHttpRequest.getRemoteAddress().getAddress().getHostAddress();
as it sad in doc: .reactive.ServerHttpRequest
represents a reactive server-side HTTP request.
Upvotes: 3
Reputation: 33524
You could also add org.springframework.http.server.ServerHttpRequest
as parameter to @RerquestMapping
annotated method and got IP address from it:
@GetMapping("/myPath")
public void someMethod(ServerHttpRequest request) {
System.out.println(request.getRemoteAddress().getAddress().getHostAddress();)
}
Upvotes: 0
Reputation: 59076
Yes, this is the correct way to achieve that. Note that if you’d like to support Forwarded or X-Forwarded-* HTTP request headers, this is something that needs to be configured at the server configuration level.
Upvotes: 2