Regarding the problem that the remote address obtained by the server is always 127.0.0.1

Project scene:

When working on the function of recording website traffic, I want to judge whether this user is logging in for the first time today by recording the ip, the recorded ip address is placed in the context, and the daily recorded ip is cleared by setting a scheduled task


Problem Description:

The ip address that the server has been getting is 127.0.0.1


Cause Analysis:

It seems that many bloggers found that the front-end set up a proxy, which caused the back-end to be unable to get the real ip address.


solution:

Cancel the proxy on the front end.

Here is the code to get the real ip

  String ip = req.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    
    
            ip = req.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    
    
            ip = req.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    
    
            ip = req.getRemoteAddr();
        }
        if (ip.indexOf(",") != -1) {
    
    
            String[] ips = ip.split(",");
            ip = ips[0].trim();
        }

Guess you like

Origin blog.csdn.net/qq_44688861/article/details/114312044