anuni
anuni

Reputation: 999

How to get client IP in webflux?

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

Answers (3)

Blednov Roman
Blednov Roman

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.

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/server/reactive/ServerHttpRequest.html

Upvotes: 3

Cherry
Cherry

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

Brian Clozel
Brian Clozel

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

Related Questions