Django

How to get an IP address in Django

First, this article is written by a Japanese man who is studying English now, so I think it may use incorrect English grammar and phrases. I would appreciate your kind understanding.

This article summarize that how to get an IP address in Django. If you’d like, read this article to the last.

Technology used

Python:3.8
Django:3.2

How to get an IP address

It is to get IP address as follows written.

def get_ip(request):
    forwarded_addresses = request.META.get('HTTP_X_FORWARDED_FOR')
    # If going through a proxy server => HTTP_X_FORWARDED_FOR
    if forwarded_addresses:
        ip = forwarded_addresses.split(',')[0]
    # If not going through a proxy server => REMOTE_ADDR
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

If client going through a proxy server then return ‘HTTP_X_FORWARDED_FOR’. Otherwise returns ‘REMOTE_ADDR’.
REMOTE_ADDR is the source IP address of a client connecting to a web server. HTTP_X_FORWARDED_FOR is http header field and this is the de facto standard for identifying the source IP address of a client connecting to a web server via a device such as a load balancer.