Django总是在我的网站上给我本地IP

时间:2013-06-19 03:06:16

标签: python django geoip

我使用django-ipware获取用户的公共IP

https://github.com/un33k/django-ipware

我的网站由虚拟机托管djnago , mod_wsgi , apache

这是我的代码

    g = GeoIP()
    ip_address = get_ip_address_from_request(self.request)
    raise Exception(ip_address)

它给了我127.0.0.1

我正从同一网络上的其他计算机访问它。

我怎样才能获得我的公共IP

我也尝试了这个

PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', )

def get_client_ip(request):
"""get the client ip from the request
"""
remote_address = 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]

return ip

它让我192.168.0.10我的本地计算机ip

1 个答案:

答案 0 :(得分:1)

django-ipware尝试获取客户端(例如浏览器)的公共(外部路由)IP地址,但是它无法执行此操作,因此,它返回“127.0.0.1”(本地环回,IPv4),指示失败为根据其文档(版本0.0.1)。

因为您的服务器在与您自己的本地计算机相同的(私有)网络上运行,所以会发生这种情况。 (192.168.x.x私有块)

您可以升级到版本django-ipware> = 0.0.5,它同时支持IPv4和& IPv6并使用如下。

# if you want the real IP address (public and externally route-able)
from ipware.ip import get_real_ip
ip = get_real_ip(request)
if ip is not None:
   # your server got the client's real public ip address
else:
   # your server doesn't have a real public ip address for user


# if you want the best matched IP address (public and/or private)
from ipware.ip import get_ip
ip = get_ip(request)
if ip is not None:
   # your server got the client's real ip address
else:
   # your server doesn't have a real ip address for user

####### NOTE:
# A `Real` IP address is the IP address of the client accessing your server 
# and not that of any proxies in between.
# A `Public` IP address is an address that is publicly route-able on the internet.