If reverse proxy software is used, when reverse proxying the URL of http://192.168.1.110:2046/ to the URL of http://www.xxx.com/, use the request.getRemoteAddr() method to obtain the IP address obtained by using the request.getRemoteAddr() method It is: 127.0.0.1 or 192.168.1.110, not the real IP of the client.
After passing 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 to the client through the forwarding address. However, in the HTTP header information of forwarding the request, X-FORWARDED-FOR information is added. Used to track the original client IP address and the server address requested by the original client. When we access http://www.xxx.com/index.jsp/, it is not actually our browser that actually accesses the index.jsp file on the server, but the proxy server first accesses http://192.168. 1.110:2046/index.jsp , the proxy server returns the accessed result to our browser. Because the proxy server accesses index.jsp, the IP obtained in index.jsp is obtained through the request.getRemoteAddr() method. It is actually the address of the proxy server, not the IP address of the client.
Then, a method of obtaining the real IP address of the client can be obtained:
The code copy is as follows:
public String getRemortIP(HttpServletRequest request) {
if (request.getHeader("x-forwarded-for") == null) {
return request.getRemoteAddr();
}
return request.getHeader("x-forwarded-for");
}
But when I visit http://www.xxx.com/index.jsp/, the returned IP address is always unknown, not 127.0.0.1 or 192.168.1.110 as shown above, and I visit http:// When /192.168.1.110:2046/index.jsp, the client's real IP address can be returned and a method is written to verify. The reason lies in Squid. The forwarded_for item in the squid.conf configuration file forwarded_for is defaulted to on. If forwarded_for is set to off, then: X-Forwarded-For: unknown
Therefore, the second method to obtain the client's real IP address can be obtained:
The code copy is as follows:
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, there is more than one value of X-Forwarded-For, but a string of IP values. Which one is the real IP of the real user side?
The answer is to take the first non-unknown valid IP string in X-Forwarded-For.
like:
The code copy is as follows:
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