In JSP, the method to obtain the client's IP address is: request.getRemoteAddr(). This method is effective in most cases. However, the real IP address of the client cannot be obtained through reverse proxy software such as Apache and Squid. If reverse proxy software is used, the IP address obtained using the request.getRemoteAddr() method is: 127.0.0.1 or 192.168.1.110, not the real IP of the client.
After going through the proxy, since an intermediate layer is added between the client and the service, the server cannot directly obtain the client's IP, and the server-side application cannot directly return the address of the forwarded request to the client. However, X-FORWARDED-FOR information is added to the HTTP header information of the forwarded request. Used to track the original client IP address and the server address requested by the original client. When we access index.jsp/, it is not actually our browser that actually accesses the index.jsp file on the server. Instead, the proxy server first accesses index.jsp, and the proxy server returns the accessed results to us. Browser, because the proxy server accesses index.jsp, the IP obtained through the request.getRemoteAddr() method in index.jsp is actually the address of the proxy server, not the IP address of the client.
So we can come up with method one to obtain the real IP address of the client:
public String getRemortIP(HttpServletRequest request) {
if (request.getHeader("x-forwarded-for") == null) {
return request.getRemoteAddr();
}
return request.getHeader("x-forwarded-for");
}
Method 2 to obtain the real IP address of the client:
public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
However, if a multi-level reverse proxy is passed, the value of X-Forwarded-For is not just one, but a series of IP values. Which one is the real IP of the real client?
The answer is to take the first non-unknown valid IP string in X-Forwarded-For. like:
X-Forwarded-For: 192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
The user’s real IP is: 192.168.1.110