2

我正在使用 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

4

1 回答 1

1

django-ipware 尝试获取客户端(例如浏览器)的公共(可外部路由)IP 地址,但它未能这样做,因此,它返回“127.0.0.1”(本地环回,IPv4),根据其文档指示失败(版本 0.0.1)。

发生这种情况是因为您的服务器与您自己的本地计算机在同一(专用)网络上运行。(192.168.xx 私有块)

您可以升级到支持 IPv4 和 IPv6 的版本 django-ipware>=0.0.5 并按如下方式使用。

# 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.
于 2014-01-01T02:12:37.240 回答