Login

Get Client IP Behind Proxy

Author:
brianjaystanley
Posted:
October 21, 2011
Language:
Python
Version:
Not specified
Score:
2 (after 2 ratings)

If your application server is behind a proxy, request.META["REMOTE_ADDR"] will likely return the proxy server's IP, not the client's IP. The proxy server will usually provide the client's IP in the HTTP_X_FORWARDED_FOR header. This util function checks both headers. I use it behind Amazon's Elastic Load Balancer (ELB).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def get_ip(request):
    """Returns the IP of the request, accounting for the possibility of being
    behind a proxy.
    """
    ip = request.META.get("HTTP_X_FORWARDED_FOR", None)
    if ip:
        # X_FORWARDED_FOR returns client1, proxy1, proxy2,...
        ip = ip.split(", ")[0]
    else:
        ip = request.META.get("REMOTE_ADDR", "")
    return ip

More like this

  1. Form field with fixed value by roam 5 days, 1 hour ago
  2. New Snippet! by Antoliny0919 1 week, 4 days ago
  3. Add Toggle Switch Widget to Django Forms by OgliariNatan 3 months ago
  4. get_object_or_none by azwdevops 6 months, 3 weeks ago
  5. Mask sensitive data from logger by agusmakmun 8 months, 2 weeks ago

Comments

Please login first before commenting.