在 Heroku 上使用 werkzeug 解析 X-Forwarded-For 获取 ip

发布于 2024-12-14 02:30:23 字数 256 浏览 3 评论 0原文

Heroku 代理从客户端到服务器的请求,因此您必须解析 X-Forwarded-For 以查找原始 IP 地址。

X-Forwarded-For 的一般格式是:

X-Forwarded-For: client1, proxy1, proxy2

在 Flask 上使用 werkzeug,我试图想出一个解决方案来访问客户端的原始 IP。

有谁知道一个好方法来做到这一点?

谢谢你!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

万水千山粽是情ミ 2024-12-21 02:30:23

Werkzeug(和 Flask)将标头存储在 werkzeug.datastructs.Headers 的实例中。您应该能够执行以下操作:

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

或者,您可以使用 request.access_route (感谢@Bastian 指出这一点!):

provided_ips = request.access_route
# First entry in the list is the client's IP

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
转身以后 2024-12-21 02:30:23

这就是我在 Django 中使用的。请参阅此 https://docs.djangoproject。 com/en/dev/ref/request-response/#django.http.HttpRequest.get_host

注意:至少在 Heroku 上 HTTP_X_FORWARDED_FOR 将是一个 IP 数组地址。第一个是客户端IP,其余的是代理服务器IP。

在settings.py中:

USE_X_FORWARDED_HOST = True

在你的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']

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']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文