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

我怕爱的太早我们不能终老 提交于 2019-12-19 03:17:41

问题


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!


回答1:


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



回答2:


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']


来源:https://stackoverflow.com/questions/8026281/parse-x-forwarded-for-to-get-ip-with-werkzeug-on-heroku

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!