How to get visitor ip address for a django project ?

Published: May 07, 2019

DMCA.com Protection Status

Example of how to get visitor ip address for a django project:

Get visitor ip address

def visitor_ip_address(request):

    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')

    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

Check if ip address is valid

To check if the ip address is valid, a solution is to use the socket nodule:

import socket

try:
    socket.inet_aton(ip)
    ip_valid = True
except socket.error:
    ip_valid = False

Ip address localisation

To find the location associated with an ip address, a solution is to use geoip2 2.9.0. To install geoip3

pip install geoip2

Download the GeoLite2-City.mmdb file on maxminds

import geoip2.database

reader = geoip2.database.Reader('./GeoLite2-City_20190430/GeoLite2-City.mmdb')

response = reader.city('128.101.101.101')

print(response.country.iso_code)
print(response.country.name)
print(response.country.names['zh-CN'])
print(response.subdivisions.most_specific.name)
print(response.subdivisions.most_specific.iso_code)
print(response.city.name)
print(response.postal.code)
print(response.location.latitude)
print(response.location.longitude)

reader.close()

References