从Http标头获取逗号分隔的ips
我在Tomcat上运行了一个Spring启动应用程序。我必须将每个ip解析为其地理位置:城市,省和国家。但是,有时我接收ip地址作为逗号分隔的String而不是单个ip地址。例如, 1.39.27.224,8.37.225.221
。
从我正在使用的Http请求中提取ip的代码:
I have a Spring boot app running on Tomcat. I have to resolve each ip to its Geolocation : city , province and Country . However,sometimes I receive ip address as a comma separated String instead of a single ip address. For example , 1.39.27.224, 8.37.225.221
.
The code to extract ip from a Http request that I am using :
public static String getIp(final HttpServletRequest request) {
PreConditions.checkNull(request, "request cannot be null");
String ip = request.getHeader("X-FORWARDED-FOR");
if (!StringUtils.hasText(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
X-Forwarded-For
可用于标识通过HTTP代理或负载均衡器连接到Web服务器的客户端的原始IP地址。
The X-Forwarded-For
can be used to identify the originating IP address of a client connecting to a web server through an HTTP proxy or load balancer.
此字段的一般格式为
X-Forwarded-For: client, proxy1, proxy2
在上面的示例中,您可以看到请求是通过proxy1传递的Proxy2发出。
In above example you can see that the request is passed through proxy1 and proxy2.
在您的情况下,您应解析此逗号分隔的字符串并读取第一个值,即客户端的IP地址。
In your case you should parse this comma separated string and read the first value which is client's IP address.
警告 - 很容易伪造一个 X-Forwarded-For
字段,这样你就可能出错了信息。
Warning - It is easy to forge an X-Forwarded-For
field so you might get wrong information.
请查看 https://en.wikipedia.org/wiki/X-Forwarded-For 以了解更多相关信息。
Please take a look at https://en.wikipedia.org/wiki/X-Forwarded-For to read more about this.