使用django来获取用户访问的IP地址
作者:我就是个世界
发表于:2011-09-24
使用django来获取用户访问的IP地址,如果用户是正常情况下,未使用代理访问,则
[code]request.META['REMOTE_ADDR'][/code]
可以获得用户的IP地址。但是有些网站服务器会使用ngix等代理http,或者是该网站做了负载均衡,导致使用remote_addr抓取到的是1270.0.1,这时使用HTTP_X_FORWARDED_FOR才获得是用户的真实IP。推荐使用以下代码:[separator]
[code]
if req.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = req.META['HTTP_X_FORWARDED_FOR']
else:
ip = req.META['REMOTE_ADDR']
[/code]
但是,也不是这样就一定能够获得IP,所以最好把代码用 try: .. except: ..包围起来,避免获取失败的时候给用户不好的体验。
[code]
try:
if req.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = req.META['HTTP_X_FORWARDED_FOR']
else:
ip = req.META['REMOTE_ADDR']
except:
pass
[/code]
更好一点的:
[code]
try:
real_ip = request.META['HTTP_X_FORWARDED_FOR']
regip = real_ip.split(",")[0]
except:
try:
regip = request.META['REMOTE_ADDR']
except:
regip = ""
[/code]
[code]request.META['REMOTE_ADDR'][/code]
可以获得用户的IP地址。但是有些网站服务器会使用ngix等代理http,或者是该网站做了负载均衡,导致使用remote_addr抓取到的是1270.0.1,这时使用HTTP_X_FORWARDED_FOR才获得是用户的真实IP。推荐使用以下代码:[separator]
[code]
if req.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = req.META['HTTP_X_FORWARDED_FOR']
else:
ip = req.META['REMOTE_ADDR']
[/code]
但是,也不是这样就一定能够获得IP,所以最好把代码用 try: .. except: ..包围起来,避免获取失败的时候给用户不好的体验。
[code]
try:
if req.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = req.META['HTTP_X_FORWARDED_FOR']
else:
ip = req.META['REMOTE_ADDR']
except:
pass
[/code]
更好一点的:
[code]
try:
real_ip = request.META['HTTP_X_FORWARDED_FOR']
regip = real_ip.split(",")[0]
except:
try:
regip = request.META['REMOTE_ADDR']
except:
regip = ""
[/code]
请发表您的评论