现在的位置: 首页 > 综合 > 正文

Tornado获取客户端IP

2017年12月27日 ⁄ 综合 ⁄ 共 659字 ⁄ 字号 评论关闭

通过网上搜索并实践发现:使用self.request.remote_ip可以获取到客户端的IP

但是如果我们使用了代理后发现获取到的IP是127.0.0.1或是服务器端IP,难道使用了代理就获取不到客户端IP?其实不是的,因为我们还需要通过进行如下设置:

Tornado支持通过 x-real-ip 或 x-forwarded-for来获取IP,但前提是需要在你的HTTPServer实例中增加xheaders=True参数

# To get remote_ip, it should set xheaders=True when initializing HTTPServer 
http_server = HTTPServer(Application(), xheaders=True)

# 或者如下
# application.listen(8080, xheaders=True)

nginx配置x-forwarded-for时只需在反向代理规则中增加一行:proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

参考链接:

1. http://www.au92.com/archives/tornado-get-remote-ip-address.html

2. http://www.au92.com/archives/tornado-get-remote-ip-address-complement.html

3. http://my.oschina.net/1123581321/blog/206496

抱歉!评论已关闭.