JavaWeb obtains the real IP address of the client

Usually we only need to use the request.getRemoteAddr(); method to obtain the client IP address in JavaWeb

If the front end uses a reverse proxy such as Nginx, we use request.getRemoteAddr(); The IP address obtained by the method is 127.0.0.1

Because after the proxy, an intermediate layer is added between the client and the server, so the server cannot directly obtain the client's IP

However, X-FORWARDED-FOR information is added in the HTTP header information of the forwarding request. Used to track the original client IP address and the server address requested by the original client

So we can use the following method to get the real IP address of the client

public String getIpAddr(HttpServletRequest request) {
        //获取请求头"x-forwarded-for"对应的value
        String ip = request.getHeader("x-forwarded-for");
        //如果获取的ip值为空
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //则获取请求头"Proxy-Client-IP"对应的value
            ip = request.getHeader("Proxy-Client-IP");
        }
        //如果获取的ip值仍为空
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //则获取请求头"WL-Proxy-Client-IP"对应的value
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        //如果以上方式获取的ip值都为空
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            //则直接获取ip地址
            ip = request.getRemoteAddr();
        }
        //返回ip地址
        return ip;
    }

But if a multi-level reverse proxy is used, the value of X-Forwarded-For is not just one, but a string of IP values

At this time, the first non-unknown valid IP string in X-Forwarded-For is the user's real IP address

Guess you like

Origin blog.csdn.net/BYZY1314/article/details/128166062