How to Get a Client IP Address in DJANGO

Fri, Aug 14, 2009

Tech Tips

Here is a small snippet to get the client’s ip address in your python code in DJANGO. You might have tried the ‘REMOTE_ADDR’ key in the request object but it always returns 127.0.0.1. To fix this, you can use the ‘HTTP_X_FORWARDED_FOR’ variable like so:


from django.http import HttpRequest

def mypage(request):
	client_address = request.META['HTTP_X_FORWARDED_FOR']
	....

The HTTP_X_FORWARDED_FOR variable stores the client’s ip when the user is going through a proxy or load balancer.

I ran into this issue when running my Django app on apache. All lookups of the ‘REMOTE_ADDR’ return localhost (127.0.0.1). This is probably a side affect of how the python module runs in apache.

Bookmark and Share
,

5 Responses to “How to Get a Client IP Address in DJANGO”

  1. Dylan Says:

    Was getting the same with REMOTE_ADDR, but works perfectly with HTTP_X_FORWARDED_FOR in my Django apps. Thanks for that!

    • Rafael Says:

      The method HTTP_X_FORWARDED_FOR is using server, into localhost faul.

      Exemple:

      from django.http import HttpRequest

      def mypage(request):
      try:
      # case server 200.000.02.001
      client_address = request.META[‘HTTP_X_FORWARDED_FOR’]
      except:
      # case localhost ou 127.0.0.1
      client_address = request.META[‘REMOTE_ADDR’]

  2. Elf M. Sternberg Says:

    Um, no.

    You’re behind a proxy. That’s why you’re getting these two different values. If your site was completely fronted to the Internet and your instance of Apache or whatever was your contact point with your clients, then your REMOTE_ADDR would be correct. In that case, HTTP_X_FORWARDED_FOR would be blank, because you had not been forwarded the request from a proxy.

  3. Elf M. Sternberg Says:

    The easiest way to get both is:

    ip_address = request.META.get(‘HTTP_X_FORWARDED_FOR’, ”) or request.META.get(‘REMOTE_ADDR’)

  4. un33k Says:

    http://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django/16203978#16203978

    pip install django-ipware
    from ipware.ip import get_ip_address_from_request
    user_ip = get_ip_address_from_request(request)