Sometimes we need to get client-side real IP, such as authentication.
in general, the IP method of the client when obtaining HTTP access in Tomcat is as follows:
Httpservletrequest.getremotehost ()
However, often we configure Apache or Nginx proxies, This is the way to get the real client IP through the above method. Through the Nginx agent, through the Httpservletrequest.getremotehost () is the address of the proxy server, Apache is the client real IP.
Nginx configuration
for Nginx, we can use the configuration:
Proxy_set_header Host $host;
Proxy_set_header x-forwarded-for $remote _addr;
In this way, an x-forwarded-for is added to the header of HTTP, which holds the client's true IP, and then in Tomcat through the following methods:
String host = Httpservletrequest.getheader ("X-forwarded-for");
Host = NULL = = Host Httpservletrequest.getremotehost (): host;
Apache configuration
by Apache Proxy, Apache will automatically increase x-forwarded-for as the client IP, but this IP is client IP, but not the client real IP, if the client in the net, This IP is the client intranet IP, in order to solve this problem, in the Apache agent before Jijiang x-forwarded-for prohibited, so still can through the httpservletrequest.getremotehost () to obtain the real IP client. Because Tomcat can not know is through the Apache proxy or Nginx agent, all, or through the way the above IP access. The Apache configuration is as follows:
Requestheader unset x-forwarded-for
solves the problem of obtaining IP in the agent case.
The complete code for obtaining an IP address, as amended, is as follows, taking into account the various agent conditions:
public static 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 ();
}
if (IP!= null && ip.length () > 0) {
string[] ips = Ip.split (",");
for (int i=0;i<ips.length;i++) {
if (Ips[i].trim (). Length () > 0 &&! " Unknown ". Equalsignorecase (Ips[i].trim ())) {
ip = Ips[i].trim ();
Break
}
}
}
return IP;
}
This can completely support all kinds of proxy IP address access to the Internet.