欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java获取不到请求的真实IP

程序员文章站 2022-03-10 15:32:55
问题最近在写博客浏览量的时候,设计了这么一个逻辑:同一个IP浏览一遍文章,5分钟内不刷新次数。就需要在服务器端得到用户的真实IP,我代码是这样写的(从网上找的方法):public static String getRealIp(HttpServletRequest request) {String ip = request.getHeader("x-forwarded-for");String unknown = "unknown";if (ip == null || ip.length()...

问题

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

}

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

本文地址:https://blog.csdn.net/leopast/article/details/110469045

相关标签: java笔记本 java