Comment obtenir l'adresse IP d'un visiteur avec django ?

Active 25 juin 2014    /    Viewed 1770    /    Comments 0    /    Edit


Exemple de comment obtenir l'adresse ip d'un visiteur sous django:

Obtenir l'adresse ip du visteur

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

Verifier si l'adresse ip est valide

On peut ensuite vérifier si l'adresse ip est valide on peut utiliser le module socket:

import socket

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

Localiser une adresse ip

Pour localiser une adresse ip, une solution possible est d'utiliser geoip2 2.9.0. Installer geoip2

pip install geoip2

Télécharger le fichier GeoLite2-City.mmdb sur 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()

Références

Liens Site
How do I get user IP address in django? stackoverflow
How to Get a Client IP Address in DJANGO Pressing the Red button
Checking for IP addresses stackoverflow
How to find location with IP address in Python? stackoverflow
IP Geolocation with Python and geoip2 youtube
Python Tutorial -Track location from IP address Geolocation geoip2 Hacking/Info-Sec youtube
geoip2 2.9.0 pypi.org
GeoLite2 Free Downloadable Databases dev.maxmind.com
python-geoip pythonhosted.org


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!