Skip to content

Instantly share code, notes, and snippets.

@uda
Created August 18, 2017 10:06
Show Gist options
  • Select an option

  • Save uda/1bc43041f889cf4256fe5288e8e4dac5 to your computer and use it in GitHub Desktop.

Select an option

Save uda/1bc43041f889cf4256fe5288e8e4dac5 to your computer and use it in GitHub Desktop.
Django Remote IP
from django.conf import settings
from django.views.generic import View
class SomeBaseView(View):
_ip_address = None
def django_ip_address(self):
if self._ip_address is None:
x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR') or ''
if x_forwarded_for.strip():
ip_list = [single_ip.strip() for single_ip in x_forwarded_for.split(',')]
ip_list.reverse()
ip = None
for ip in ip_list:
if ip not in settings.PROXY_SERVERS:
break
self._ip_address = ip
if not self._ip_address:
self._ip_address = self.request.META.get('REMOTE_ADDR', '')
return self._ip_address
"""
Example of known internal proxies to ignore
"""
PROXY_SERVERS = (
'10.4.40.3',
'172.23.23.5',
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment