Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active April 27, 2021 18:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rponte/2166107f65d3f8523e1498ed9b294b82 to your computer and use it in GitHub Desktop.
Save rponte/2166107f65d3f8523e1498ed9b294b82 to your computer and use it in GitHub Desktop.
SpringBoot: how to obtain the user IP address?
package br.com.zup.edu.nossocartao.propostas.shared.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.stream.Stream;
@Component
@RequestScope
public class ClientHostResolver {
private final HttpServletRequest request;
@Autowired
public ClientHostResolver(HttpServletRequest request) {
this.request = request;
}
/**
* Resolves client IP address when application is behind a NGINX or other reverse proxy server
*/
public String resolve() {
String xRealIp = request.getHeader("X-Real-IP"); // used by Nginx
String xForwardedFor = request.getHeader("X-Forwarded-For"); // used by the majority of load balancers
String remoteAddr = request.getRemoteAddr(); // otherwise uses the remote IP address obtained by our Servlet container
// returns the first non null
return Stream.of(xRealIp, xForwardedFor, remoteAddr)
.filter(Objects::nonNull)
.findFirst().orElse(null);
}
}
@rafaelpontezup
Copy link

Important note: the X-Forwarded-For header may return a list of IP adresses, for example:

X-Forwarded-For: client, proxy1, proxy2

X-Forwarded-For: 203.0.113.195, 70.41.3.18, 150.172.238.178
X-Forwarded-For: 203.0.113.195
X-Forwarded-For: 2001:db8:85a3:8d3:1319:8a2e:370:7348

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment