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

标签 python django geoip

我正在使用 django-ipware 来获取用户的公共(public) 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

我正在从同一网络上的另一台计算机访问它。

如何获取我的公共(public)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

最佳答案

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

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

您可以升级到版本 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.

关于python - Django 总是在我的网站上给我本地 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17182257/

相关文章:

mysql - 球坐标系上距离另一点最近的点

mysql - Geoip 与 MySQL

c++ - 用visual studio 2010编译Maxmind C库

python - 如何使用 python 在 json 中动态修改我的 datetime 对象?

Python如何获取一个数据框中但不在第二个数据框中的值

Python 解释器无法处理导入的模块?

mysql - 频繁更新django模型的某一字段

django - 在 Django 中创建用户个人资料页面

python - abaqus脚本: TypeError: cannot concatenate 'str' and 'Set' objects

python - Django Twitter 克隆。如何限制用户多次点赞一条推文?