The real ip of the client in the http request

  

private String getRemoteAddr() {
        String ip = "";
        String unknow = "unknown";
        try {
            ip =request.getHeader("x-forwarded-for");
            if(ip == null || ip.length() == 0 || unknow.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if(ip == null || ip.length() == 0 || unknow.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
       if(ip == null || ip.length() == 0 || unknow.equalsIgnoreCase(ip)) {
                ip =request.getRemoteAddr();
            }
       return ip.split(",")[0]; 
     }
catch (Exception e) { // } }

  As can be seen from the above, to obtain the external network IP, it is used to obtain the header

1. x-forwarded-for
for this, to understand, summarize the experience of others:
when you use a proxy, the web server does not know your real IP, in order to avoid this situation, the proxy server usually increases A header information called x_forwarded_for, add the client IP that connects to it (that is, the IP of your Internet machine) to this header information, so as to ensure that the web server of the website can obtain the real IP,

X-Forwarded-For is an extension header. The HTTP/1.1 (RFC 2616) protocol does not define it. It was originally introduced by the caching proxy software Squid to represent the real IP of the HTTP requester. It has now become a de facto standard and is used by major HTTP proxies, Forwarding services such as load balancing are widely used and are written into the  RFC 7239  (Forwarded HTTP Extension) standard.

The X-Forwarded-For request header format is very simple, like this:

X-Forwarded-For: client, proxy1, proxy2

It can be seen that the content of XFF consists of multiple parts separated by "English comma + space", the first is the IP of the device farthest from the server, and then the IP of each level of proxy device.

If an HTTP request goes through three proxies Proxy1, Proxy2, and Proxy3 before reaching the server, the IPs are IP1, IP2, and IP3 respectively, and the user's real IP is IP0, then according to the XFF standard, the server will eventually receive the following information:

X-Forwarded-For: IP0, IP1, IP2
总结是:在使用nginx等反向代理服务器的时候,是必须使用X-Forward-For来获取用户IP地址的(此时Remote Address是nginx的地址),因为此时X-Forward-For中的地址是由nginx写入的,而nginx是可信任的。不过此时要注意,要禁止web对外提供服务。
2、Remote Address
Remote Address代表的是当前HTTP请求的远程地址,即HTTP请求的源地址。HTTP协议在三次握手时使用的就是这个Remote Address地址,在发送响应报文时也是使用这个Remote Address地址。因此,如果请求者伪造Remote Address地址,他将无法收到HTTP的响应报文,
此时伪造没有任何意义。这也就使得Remote Address默认具有防篡改的功能。如果Http请求经过代理服务器转发,则这种情况,用户的真实ip会丢失,所以才有了 “
X-Forwarded-For”的方式。


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325344408&siteId=291194637