Getting comma-separated ips from an Http header

I have a Spring boot application running on Tomcat. I have to allow each ip for my geolocation: cities, provinces and countries. However, sometimes I get the 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 for extracting ip from an Http request that I use:

 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; } 
0
source share
1 answer

X-Forwarded-For can be used to identify the outgoing IP address of a client connecting to the web server through an HTTP proxy or load balancer.

The general format of this field

 X-Forwarded-For: client, proxy1, proxy2 

In the above example, you can see that the request is passed through proxy1 and proxy2.

In your case, you have to parse this comma and read the first value, which is the client IP address.

A warning. It's easy to fake the X-Forwarded-For field so you can get the wrong information.

Please see https://en.wikipedia.org/wiki/X-Forwarded-For to find out more about this.

+2
source

Source: https://habr.com/ru/post/1269685/


All Articles