Login

Get Client IP Behind Proxy

Author:
brianjaystanley
Posted:
October 21, 2011
Language:
Python
Version:
Not specified
Tags:
request ip
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. Add get_addr() method to request object by nikmolnar 2 years, 8 months ago
  2. Single Django App behind multiple Apache Proxies by chadmaine 8 years, 4 months ago
  3. Effective content caching for mass-load site using redirect feature by nnseva 4 years, 1 month ago
  4. django soaplib test client by erny 6 years, 5 months ago
  5. Use the development server on the network by perevilas 4 years, 5 months ago

Comments

Please login first before commenting.