Example of how to get visitor ip address for a django project:
Table of contents
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
Links | 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 |