how to get user ip address

The user's IP address may be hidden or modified, such as using proxy servers, VPN and other tools, so that the user's real IP address cannot be accurately obtained.
In addition to the above special circumstances, in general, user access may go through the following link:
front-end—>nginx—>gateway—>service. Under normal circumstances, the IP addresses acquired by the latter three can only be the IP addresses of the previous one. For example, the gateway can only obtain the IP address of nginx. So in general, we need to obtain the user ip from the front end, and then pass it on through the header.
nginx configuration

server {
    
    
    listen 80; #访问端口
    server_name your_domain.com; #访问域名

    location / {
    
    
        proxy_pass http://your_backend;  # nginx能访问的后端网关地址
        proxy_set_header X-Real-IP $remote_addr;  # 设置请求头中的 X-Real-IP 字段为用户真实 IP 地址

    }
}

Gateway configuration global interceptor implements GlobalFilter pass ip

        ServerHttpRequest request = exchange.getRequest().mutate().
                header(CommonConstants.REAL_IP,exchange.getRequest().getRemoteAddress().getHostString()).build();

Obtained in the service

        /**
         * HttpServletRequest在微服务中通过获取请求头从而获取到真实的客户端IP
         */
        String ip = request.getHeader(CommonConstants.REAL_IP);

Guess you like

Origin blog.csdn.net/qq_56533553/article/details/132634718