Get users's IP, even if they're behind proxies
This is from my improvement of an answer on stackoverflow about user's IP address, taking proxies into account.
If the user is behind a proxy, the HTTPXFORWARDED_FOR header contains a comma seperated list of IP's. The first IP is the clien'ts internal IP address, followed by one or more proxies or load balancers that may have handled the request. Read more about the header on Wikipedia.
This solution focuses on getting the external IP address of the last client (the proxy address), which is the right-most address in the header.
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
Written by Sævar Öfjörð Magnússon
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Related Tags
#django
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#