Get the client's IP address in Django

Direct access only

If you've decided that your client will have direct access to Django, you can get an IP address by simply looking at the HTTP header 'REMOTE_ADDR'.

views.py


from django.http import HttpResponse
from django.views import View

class MyView(View):
    def get(self, request):
        #From the request object'REMOTE_ADDR'Get the header.
        client_addr = request.META.get('REMOTE_ADDR')

        #The acquired address is returned as it is to check the operation.
        return HttpResponse(client_addr)

Supports reverse proxy

However, with the above method, if there is a reverse proxy such as Nginx between the client and Django, the IP address that can be obtained by 'REMOTE_ADDR' will be the address of the reverse proxy (for example, Nginx is on the same host). If there is, it will be 127.0.0.1).

If the transfer is made more than once in the middle, you can also refer to the HTTP header 'HTTP_X_FORWARDED_FOR' to get the IP address of the transfer route as a comma-separated string, so get the client IP address from this first element. can do.

Also, if there is no 'HTTP_X_FORWARDED_FOR' header, it is a direct access, so get it with 'REMOTE_ADDR' as above.

views.py


from django.http import HttpResponse
from django.views import View

class MyView(View):
    def get(self, request):
        # 'HTTP_X_FORWARDED_FOR'Obtain the IP address of the transfer route by referring to the header.
        forwarded_addresses = request.META.get('HTTP_X_FORWARDED_FOR')
        if forwarded_addresses:
            # 'HTTP_X_FORWARDED_FOR'If there is a header:Get the first element of the transfer route.
            client_addr = forwarded_addresses.split(',')[0]
        else:
            # 'HTTP_X_FORWARDED_FOR'If there is no header:Because it is a direct connection'REMOTE_ADDR'Refer to the header.
            client_addr = request.META.get('REMOTE_ADDR')

        #The acquired address is returned as it is to check the operation.
        return HttpResponse(client_addr)

use ipware

Install django-ipware with pip.

python


pip3 install django-ipware

You can import it and use the get_client_ip function to get the client's address in just one line, and of course it supports reverse proxies.

views.py


from django.http import HttpResponse
from django.views import View
from ipware import get_client_ip

class MyView(View):
    def get(self, request):
        client_addr, _ = get_client_ip(request)

        return HttpResponse(client_addr)

The referenced HTTP header gets the client's address by default, in addition to 'HTTP_X_FORWARDED_FOR' and 'REMOTE_ADDR'.

python


 # The default meta precedence order
 IPWARE_META_PRECEDENCE_ORDER = (
     'HTTP_X_FORWARDED_FOR', 'X_FORWARDED_FOR',  # <client>, <proxy1>, <proxy2>
     'HTTP_CLIENT_IP',
     'HTTP_X_REAL_IP',
     'HTTP_X_FORWARDED',
     'HTTP_X_CLUSTER_CLIENT_IP',
     'HTTP_FORWARDED_FOR',
     'HTTP_FORWARDED',
     'HTTP_VIA',
     'REMOTE_ADDR',
 )

You can also override the default priority with the specified priority when calling the get_client_ip function.

python


client_addr, is_routable = get_client_ip(request, request_header_order=['X_FORWARDED_FOR', 'REMOTE_ADDR'])

Reference link

Stack Overflow "How do I get user IP address in django?" https://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django

GitHub - un33k/django-ipware "A Django application to retrieve client's IP address" https://github.com/un33k/django-ipware

Recommended Posts

Get the client's IP address in Django
Get the query string (query string) in Django
Get your own IP address in Python
Get local IP address
[Django] Change the Default IP address of the runserver command
Get all IP addresses of instances in the autoscaling group
Get the desktop path in Python
Get the script path in Python
Switch the language displayed in Django 1.9
Get parameter values ​​in Django templates
Get the value from the [Django] Form
Get the desktop path in Python
The meaning of ".object" in Django
Get the host name in Python
Get the address from the zip code
[OCI] Python script to get the IP address of a compute instance in Cloud Shell
Get the IPv4 address assigned to the network interface in code (Linux)
Django ~ Let's display it in the browser ~
Get the top nth values in Pandas
Resolve the Address already in use error
Get query parameters for GET requests in Django
To get a local IP address programmatically
I can't get the element in Selenium!
Get the EDINET code list in Python
Get the address from latitude and longitude
Try hitting the Spotify API in Django.
Get only the text from the Django form.
Script to register the IP address used by wercker in Security Group
[Python] Get the files in a folder with Python
Get the weather in Osaka via WebAPI (python)
The easiest way to get started with Django
Models in Django
Get the caller of a function in Python
Get only the subclass elements in a list
Get the X Window System window title in Python
Set a fixed IP in the Linux environment
[Django] Create a form that automatically fills in the address from the zip code
How to get the files in the [Python] folder
Specify the view URL in your Django template
Get only the address part of NIC (eth0)
The story of viewing media files in Django
[Django] css in the project cannot be read
Use pygogo to get the log in json.
Forms in Django
A tool to insert the country name and country code in the IP address part
Learning notes for the migrations feature in the Django framework (2)
How to get the variable name itself in python
How to get multiple model objects randomly in Django
Get the file name in a folder using glob
How to get the number of digits in Python
[Python] Get the numbers in the graph image with OCR
[python] Get the list of classes defined in the module
[Django] Perform Truncate Table (delete all data in the table)
Set the form DateField to type = date in Django
Get the result in dict format with Python psycopg2
Get the size (number of elements) of UnionFind in Python
Get the value selected in Selenium Python VBA pull-down
Learning notes for the migrations feature in the Django framework (3)
Learning notes for the migrations feature in the Django framework (1)
[Django 2.2] Sort and get the value of the relation destination
Get the URL of the HTTP redirect destination in Python