Obtain the real IP address of the user based on HttpServletRequest,
Cause:
When we obtain the Client IP address through a request, our servers usually reverse proxy their own servers for the purpose of protecting information or load balancing. In this case, if we use request. getRemoteAddr ();, we may obtain the IP address of our proxy server, but cannot obtain the ip address of the user request.
Solution:
The following lists the forwarding service request headers developed by each proxy server. These request headers are not standard http request headers. Not all proxies will carry these request headers, therefore, this method can only obtain the real ip address as much as possible, but it cannot be ensured that the real ip address can be obtained, and the ip address obtained in the request header of the proxy server can be forged.
Parameters:
X-Forwarded-For: Squid service proxy
Proxy-Client-IP: apache service Proxy
WL-Proxy-Client-IP: weblogic Service Proxy
HTTP_CLIENT_IP: some proxy servers
X-Real-IP: nginx Service Proxy
Public static String getIPAddress (HttpServletRequest request) {String ip = null;
// X-Forwarded-For: Squid service proxy String ipAddresses = request. getHeader ("X-Forwarded-");
If (ipAddresses = null | ipAddresses. length () = 0 | "unknown". equalsIgnoreCase (ipAddresses )){
// Proxy-Client-IP: apache service Proxy ipAddresses = request. getHeader ("Proxy-Client-IP ");}
If (ipAddresses = null | ipAddresses. length () = 0 | "unknown". equalsIgnoreCase (ipAddresses )){
// WL-Proxy-Client-IP: weblogic Service Proxy ipAddresses = request. getHeader ("WL-Proxy-Client-IP ");}
If (ipAddresses = null | ipAddresses. length () = 0 | "unknown". equalsIgnoreCase (ipAddresses )){
// HTTP_CLIENT_IP: some proxy servers ipAddresses = request. getHeader ("HTTP_CLIENT_IP ");}
If (ipAddresses = null | ipAddresses. length () = 0 | "unknown". equalsIgnoreCase (ipAddresses )){
// X-Real-IP: nginx Service proxy ipAddresses = request. getHeader ("X-Real-IP ");}
// If some networks use multi-layer proxies, multiple ip addresses are obtained, which are generally separated by commas, and the first ip address is the real IP address of the client if (ipAddresses! = Null & ipAddresses. length ()! = 0) {ip = ipAddresses. split (",") [0];}
// Still cannot be obtained, and then use request. getRemoteAddr (); get if (ip = null | ip. length () = 0 | "unknown ". equalsIgnoreCase (ipAddresses) {ip = request. getRemoteAddr ();} return ip ;}
Legacy problems:
Windows platform passed the test. linux is unknown.
23:38:06