When building a web application, it’s often necessary to retrieve the IP address of the user who is accessing the application. This information can be useful for various purposes, such as security, analytics, and customization. In this tutorial, we will explore how to retrieve both IPv4 and IPv6 addresses of a user in a Spring Boot application.

Retrieving User IP Address

In Spring Boot, we can retrieve the IP address of a user by injecting a HttpServletRequest object into our controller class and calling its getRemoteAddr() method. For example:

@RestController
public class UserController {

    @Autowired
    private HttpServletRequest request;

    @GetMapping("/user/ip")
    public String getUserIP() {
        String ipAddress = request.getRemoteAddr();
        return ipAddress;
    }
}

In the above code, we have injected a HttpServletRequest object using the @Autowired annotation and defined a getUserIP() method that returns the IP address of the user. The getRemoteAddr() method of the HttpServletRequest object returns the IP address of the client or the last proxy that sent the request.

However, this method may not always return the correct IP address. In some cases, the IP address may be the address of a proxy server or load balancer rather than the actual user’s IP address. To obtain the correct IP address, we can check for the X-Forwarded-For header, which is a standard header used by proxies to indicate the originating IP address of a client connecting to a web server through the proxy. Here’s an updated version of the code that checks for the X-Forwarded-For header:

@RestController
public class UserController {

    @Autowired
    private HttpServletRequest request;

    @GetMapping("/user/ip")
    public String getUserIP() {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }
}

In the above code, we first check for the X-Forwarded-For header using the getHeader() method of the HttpServletRequest object. If the header is not present or its value is empty or “unknown”, we fall back to the getRemoteAddr() method to obtain the IP address.