How to Get a Client IP Address in DJANGO using python?


Question


I have a django website developed with python programming. I want to store the viewers unique ip address when someone access my site. For that I included a code like below.

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

But it always returns the following ip address "127.0.0.1". What am I doing wrong? Please somebody help me to solve my clients ip address fetching issue.Thanks in advance


Answer 1:


you are getting 127.0.0.1 because you are visiting the page with a loopback adress in your local machine

when you deploy your app and open it in a browser, you will get your public IP.




Answer 2:


127.0.0.1 is a special IP address used for "loopback" connections. This means that your local machine is both the client AND the host. You have a few options if this isn't acceptable:

  • Add a middlewear plugin to modify the HTTP_X_FORWARDED_FOR header (testing purposes only)
  • Issue your client requests from a another host (a separate box or a virtual machine on the local host)
  • Instead of using a browser, use curl and spoof the appropriate header:

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




Answer 3:


<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>


来源:https://stackoverflow.com/questions/27702217/how-to-get-a-client-ip-address-in-django-using-python


码神部落- 版权声明 1、本主题所有言论和图片纯属会员个人意见,与码神部落立场无关。
2、本站所有主题由该帖子作者发表,该帖子作者爷万人跪拜码神部落享有帖子相关版权。
3、码神部落管理员和版主有权不事先通知发贴者而删除本文。
4、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者爷万人跪拜码神部落的同意。
5、帖子作者须承担一切因本文发表而直接或间接导致的民事或刑事法律责任。
6、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责。
7、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意。

最新回复 (0)
    • 码神部落
      2
        立即登录 立即注册 GitHub登录
返回
发新帖
作者最近主题: