JSP gets the code for the real IP address

  • 2020-05-24 05:57:46
  • OfStack

However, after passing Apache, Squid and other reverse agent software, the real IP address of the client cannot be obtained. If the reverse proxy software is used, the IP address obtained using the request.getRemoteAddr () method is 127.0.0.1 or 192.168.1.110 and is not the real IP of the client.
After the proxy, the server cannot directly get to the client IP due to the middle layer between the client and the service, and the server-side application cannot directly return to the client via the forwarding address. However, the X-FORWARDED-FOR message was added to the HTTP header to forward the request. To track the original client IP address and the server address requested by the original client. . When we visit index jsp /, it's not our real access to the server browser index. jsp files, but by the proxy server to access first index. jsp, proxy server and then will return to give us access to the results of the browser, because is a proxy server to access index jsp, so index jsp by request. getRemoteAddr () method to obtain IP is actually a proxy server address, It is not the client's IP address.
Thus, the method 1 to obtain the true IP address of the client can be obtained:
 
public String getRemortIP(HttpServletRequest request) { 
if (request.getHeader("x-forwarded-for") == null) { 
return request.getRemoteAddr(); 
} 
return request.getHeader("x-forwarded-for"); 
} 

Method 2 to get the true 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 multilevel reverse proxy is passed, the value of X-Forwarded-For is not only one, but a series of IP values. Which is the real IP of the real client?
The answer is to take the first valid IP string in X-Forwarded-For that is not unknown. Such as:
X-Forwarded-For: 192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
User real IP: 192.168.1.110

Related articles: