We know that in jsp, the method to obtain the IP address of the webpage client is request. getremoteaddr (), which 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 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, the x-forwarded-for information is added to the http header of 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:
Public string getremortip (httpservletrequest request ){
If (request. getheader ("x-forwarded-for") = null ){
Return request. getremoteaddr ();
}
Return request. getheader ("x-forwarded-");
}
Method 2:
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.
The real IP address of the browser can be obtained through the above method.