Java获取不到请求的真实IP

2021-03-12 06:29

阅读:532

标签:ase   sign   sig   代理   https   servlet   dock   header   用户   

问题

最近在写博客浏览量的时候,设计了这么一个逻辑:同一个IP浏览一遍文章,5分钟内不刷新次数。就需要在服务器端得到用户的真实IP,我代码是这样写的(从网上找的方法):

public static String getRealIp(HttpServletRequest request) {
	String ip = request.getHeader("x-forwarded-for");
	String unknown = "unknown";
	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.getHeader("HTTP_CLIENT_IP");
	}
	if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
		ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	}
	if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
		ip = request.getRemoteAddr();
	}
	return ip;
}

发现得到的IP总172开头的IP,我查了下是本地局域网的IP,我的项目又是docker布署的,这又记我联想到docker内部的IP。。。

解决办法

最后才发现nginx代理接口的时候,需要做获取IP的配置

location ^~ /api {
    proxy_pass http://127.0.0.1:8110/;
    proxy_read_timeout  90;
    #得到请求真实IP
    proxy_set_header    X-Real-IP        $remote_addr;
    proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header    HTTP_X_FORWARDED_FOR $remote_addr;
    proxy_set_header    X-Forwarded-Proto $scheme;
    proxy_redirect      default;

}

加上面面的配置,问题解决!

Java获取不到请求的真实IP

标签:ase   sign   sig   代理   https   servlet   dock   header   用户   

原文地址:https://www.cnblogs.com/pigmen/p/14088605.html


评论


亲,登录后才可以留言!