questions post
questions post

Reputation: 57

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

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

Upvotes: 2

Views: 7442

Answers (3)

Rajan Mandanka
Rajan Mandanka

Reputation: 2053

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

Upvotes: 0

rob
rob

Reputation: 116

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"

Upvotes: 1

doniyor
doniyor

Reputation: 37846

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.

Upvotes: 3

Related Questions