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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.