How can Java retrieve the request’s IP address?
In Java, you can use the following code to get the IP address of a request:
import javax.servlet.http.HttpServletRequest;
public String getIpAddress(HttpServletRequest request) {
String ipAddress = request.getHeader("X-Forwarded-For");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
return ipAddress;
}
This code examines the HTTP header information to attempt to retrieve the requested IP address. Initially, it tries to obtain the IP address from the “X-Forwarded-For” header, which is a common proxy server setting that can provide the actual client IP address. If unsuccessful, it will then try to retrieve the IP address from the “Proxy-Client-IP” and “WL-Proxy-Client-IP” headers. Finally, if it is still unable to retrieve the IP address, it will use the request.getRemoteAddr() method to obtain the final IP address.
Please note that this code may not be suitable for all environments due to varying configurations of application servers and proxy servers. You may need to make adjustments based on your specific circumstances.