Request Method Client IP: request. getremoteaddr () Output: 192.168.0.106
Client Host Name: request. getremotehost () Output: ABC
Request. getheader ("host") Output: 192.168.0.1: 8080
Web Server Name: request. getservername () Output: 192.168.0.1
Request. getserverport () Output: 8080
In JSP, the method for obtaining the Client IP address is request. getremoteaddr (), which is valid 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, 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/, our browser does not actually access the index. jsp file on the server, but first accesses index. jsp by the proxy server,
The proxy server then returns the access result to our browser, because the proxy server accesses index. jsp,
Therefore, the IP obtained through the request. getremoteaddr () method in index. jsp 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 are more than one X-forwarded-for value, but a string of IP values,
Which is the real IP address of the real 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, and 192.168.1.100.