Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Heroku proxies requests from a client to server, so you have to parse the X-Forwarded-For to find the originating IP address.

The general format of the X-Forwarded-For is:

X-Forwarded-For: client1, proxy1, proxy2

Using werkzeug on flask, I'm trying to come up with a solution in order to access the originating IP of the client.

Does anyone know a good way to do this?

Thank you!

like image 956
Jack P. Avatar asked Nov 06 '11 09:11

Jack P.


2 Answers

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

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

Alternately, you could use request.access_route (thanks @Bastian for pointing that out!):

provided_ips = request.access_route
# First entry in the list is the client's IP
like image 140
Sean Vieira Avatar answered Oct 26 '22 23:10

Sean Vieira


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

Note: At least on Heroku HTTP_X_FORWARDED_FOR will be an array of IP addresses. The first one is the client IP the rest are proxy server IPs.

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']
like image 31
David Dehghan Avatar answered Oct 26 '22 23:10

David Dehghan