However, the real IP address of the client cannot be obtained through reverse proxy software such as Apache and squid. 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, rather than the real IP address of the client.
After proxy, because the intermediate layer is added between the client and the service, the server cannot directly obtain the IP address of the client, and the server application cannot directly return the IP address of the forwarded request to the client. However, X-FORWARDED-FOR information is added in the HTTP header information that forwards the request. It is used to track the original Client IP address and the server address of the original client request. When we access index. JSP/is not actually the index on the server accessed by our browser. JSP file, but the index is first accessed by the proxy server. JSP, the proxy server returns the access results to our browser, because the proxy server accesses the index. JSP, so index. in JSP, request. the IP obtained by getremoteaddr () is actually the proxy server address, not the client IP address.
So we can obtain the real IP address of the client. Method 1:
CopyCode The Code is as follows: Public String getremortip (httpservletrequest request ){
If (request. getheader ("X-forwarded-for") = NULL ){
Return request. getremoteaddr ();
}
Return request. getheader ("X-forwarded-");
}
Method 2:Copy codeThe Code is as follows: Public String getipaddr (httpservletrequest request ){
String IP = request. getheader ("X-forwarded-");
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 will be more than one X-forwarded-for value, but a string of IP values. Which is the real IP address of the client?
The answer is to take the first valid IP string not unknown in X-forwarded-. For example:
X-forwarded-for: 192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
The user's real IP address is 192.168.1.110.