Parse X-Forwarded-For to get werkzeug ip on Heroku

Heroku proxy requests from client to server, so you need to parse X-Forwarded-For to find the source IP address.

General X-Forwarded-For format:

X-Forwarded-For: client1, proxy1, proxy2 

Using werkzeug on a flask, I am trying to find a solution to access the client's source IP address.

Does anyone know a good way to do this?

Thanks!

+6
source share
2 answers

Werkzeug (and Flask) store the headers in an instance of werkzeug.datastructures.Headers . You should do something like this:

 provided_ips = request.headers.getlist("X-Forwarded-For") # The first entry in the list should be the client IP. 

Alternatively, you can use request.access_route (thanks @Bastian for pointing this out!):

 provided_ips = request.access_route # First entry in the list is the client IP 
+15
source

This is what I use in Django. See https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.get_host

Note. At least Heroku's HTTP_X_FORWARDED_FOR will have an array of IP addresses. The first is the IP address of the client, the rest are the IP addresses of the proxy server.

in settings.py:

 USE_X_FORWARDED_HOST = True 

in your views.py:

 if 'HTTP_X_FORWARDED_FOR' in request.META: ip_adds = request.META['HTTP_X_FORWARDED_FOR'].split(",") ip = ip_adds[0] else: ip = request.META['REMOTE_ADDR'] 
+2
source

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


All Articles