EN
Spring Boot - get client IP address from request (HttpServletRequest)
13 points
In this short article, we would like to show how to get a client IP address from a request in Spring Boot Web Application in Java.

Steps:
- Integrate below code with your web site,
- Run your Spring Boot Web Application,
- Open one of the following addresses in the web browser:
http://localhost/client-ip-address
for development (on localhost),https://my-domain.com/client-ip-address
for production.
ClientIPAddressController.java
file:
xxxxxxxxxx
1
package com.example.controllers;
2
3
import com.example.utils.HttpUtils;
4
import org.springframework.http.MediaType;
5
import org.springframework.stereotype.Controller;
6
import org.springframework.web.bind.annotation.RequestMapping;
7
import org.springframework.web.bind.annotation.RequestMethod;
8
import org.springframework.web.bind.annotation.ResponseBody;
9
10
import javax.servlet.http.HttpServletRequest; // or: jakarta.servlet.http.HttpServletRequest
11
12
13
public class ClientIPAddressController {
14
15
(
16
method = RequestMethod.GET,
17
value = "/client-ip-address",
18
produces = MediaType.TEXT_PLAIN_VALUE
19
)
20
21
public String getClientIPAddress(HttpServletRequest request) {
22
String ip = HttpUtils.getRequestIP(request);
23
return "Client IP Address: " + ip;
24
}
25
}
HttpUtils.java
file:
xxxxxxxxxx
1
package com.example.utils;
2
3
import javax.servlet.http.HttpServletRequest; // or: jakarta.servlet.http.HttpServletRequest
4
5
public final class HttpUtils {
6
7
private static final String[] IP_HEADERS = {
8
"X-Forwarded-For",
9
"Proxy-Client-IP",
10
"WL-Proxy-Client-IP",
11
"HTTP_X_FORWARDED_FOR",
12
"HTTP_X_FORWARDED",
13
"HTTP_X_CLUSTER_CLIENT_IP",
14
"HTTP_CLIENT_IP",
15
"HTTP_FORWARDED_FOR",
16
"HTTP_FORWARDED",
17
"HTTP_VIA",
18
"REMOTE_ADDR"
19
20
// you can add more matching headers here ...
21
};
22
23
private HttpUtils() {
24
// nothing here ...
25
}
26
27
public static String getRequestIP(HttpServletRequest request) {
28
for (String header: IP_HEADERS)
29
String value = request.getHeader(header);
30
if (value == null || value.isEmpty()) {
31
continue;
32
}
33
String[] parts = value.split("\\s*,\\s*");
34
return parts[0];
35
}
36
return request.getRemoteAddr();
37
}
38
}
Note:
IP_HEADERS
are useful to get a client IP address when we use some other application that may cover our server, e.g.VirtualServers
, load balancers, etc.