Search code examples
pythonherokuipflaskwerkzeug

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!


Solution

  • 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