【发布时间】:2015-02-26 10:15:15
【问题描述】:
我有一个用 python 编程开发的 django 网站。当有人访问我的网站时,我想存储查看者的唯一 IP 地址。为此,我包含了如下代码。
def get_client_ip(request):
"""get the client ip from the request
"""
#remote_address = request.META.get('REMOTE_ADDR')
remote_address = request.META.get('HTTP_X_FORWARDED_FOR')or request.META.get('REMOTE_ADDR')
# set the default value of the ip to be the REMOTE_ADDR if available
# else None
ip = remote_address
# try to get the first non-proxy ip (not a private ip) from the
# HTTP_X_FORWARDED_FOR
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
proxies = x_forwarded_for.split(',')
# remove the private ips from the beginning
while (len(proxies) > 0 and proxies[0].startswith(PRIVATE_IPS_PREFIX)):
proxies.pop(0)
# take the first ip which is not a private one (of a proxy)
if len(proxies) > 0:
ip = proxies[0]
print"IP Address",ip
return ip
但它总是返回以下 IP 地址“127.0.0.1”。我究竟做错了什么?请有人帮我解决我的客户 IP 地址获取问题。在此先感谢
【问题讨论】:
-
但它总是返回下面的ip地址“127.0.0.1”。我做错了什么? -- 没有从另一台机器发送请求?
-
您是否从一台服务器以外的机器访问了您的网站?在remote_address初始化后添加打印检查是否有HTTP_X_FORWARDED_FOR。
-
专业提示:任何人都可以简单地欺骗 HTTP_X_FORWARDED_FOR 标头,这意味着它绝对不可靠。我可以利用您的代码并告诉您“hello world”是我的 IP 地址。所以我不建议将它用于任何重要的事情。
-
@questions 帖子 - 你对
PRIVATE_IPS_PREFIX有什么用?