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