How do I get user IP address in django?

How do I get user IP address in django?

Asked on November 12, 2018 in Python.
Add Comment


  • 3 Answer(s)

      Try this code to get user IP address:

    def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
    ip = x_forwarded_for.split(',')[0]
    else:
    ip = request.META.get('REMOTE_ADDR')
    return ip
    

      Check the  reverse proxy (if any) configured correctly , then just pass the request as argument to it.

      Note: the above uses the first item in X-Forwarded-For, So the  last item should be used.

    get_client_ip(request)
    
    Answered on November 12, 2018.
    Add Comment

      Some routers don’t respect the protocol, and seeing the  internal ips as the first value of the list is possible.So,Instead of taking the first ip in the X_FORWARDED_FOR list,Take the first one which in not a known internal ip for improvement:

    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
    
    Answered on November 12, 2018.
    Add Comment

    Use this simple solution:

    request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR')).split(',')[-1].strip()
    
    
    Answered on November 12, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.