如何使用python在DJANGO中获取客户端IP地址?

时间:2014-12-30 08:49:24

标签: python django

我有一个用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地址提取问题。谢谢提前

3 个答案:

答案 0 :(得分:0)

您将获得127.0.0.1,因为您正在访问本地计算机中带有环回地址的页面

当您部署应用并在浏览器中打开它时,您将获得公共IP。

答案 1 :(得分:0)

127.0.0.1是一个特殊的IP地址,用于" loopback"连接。这意味着您的本地计算机既是客户端又是主机。如果这是不可接受的,您有几个选择:

  • 添加中间件插件以修改HTTP_X_FORWARDED_FOR标头(仅限测试目的)
  • 从另一台主机(本地主机上的单独的盒子或虚拟机)发出客户端请求
  • 不使用浏览器,而是使用curl并欺骗相应的标题:

    curl --header "X-Forwarded-For: 192.168.1.1" "http://127.0.0.1"

答案 2 :(得分:0)

<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
    <script>
        function systemip(){`enter code here`
        document.getElementById("ip").value = myip
        console.log(document.getElementById("ip").value)
        }
    </script>