亲宝软件园·资讯

展开

Java获取真实IP Java无法获取真实IP解决方案

码农记事本 人气:0

问题

最近在写博客浏览量的时候,设计了这么一个逻辑:同一个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;

}

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

加载全部内容

相关教程
猜你喜欢
用户评论