Geolocating an IP Address with Python and Geocoder
Obtaining the geographical location of an IP address can be valuable for various applications, from web analytics to cybersecurity. In this tutorial, we will explore how to determine the location of an IP address using Python, and Geocoder and Folium libraries.
IP Geolocation with Geocoder
Geocoder is a Python library that simplifies working with geocoding provider such as Google, Bing and OSM using Python. This Python library provides a straightforward method for IP geolocation.
Geocoder Installation
To get started, you’ll need to install Geocoder using PIP:
pip install geocoder
You can also install Geocoder using Conda:
conda install -c conda-forge geocoder
IP Geolocation
Once Geocoder is installed, you must import the library into Python and assign an IP address to a geocoder.ip
variable.
You can then obtain the city and the coordinates (latitude and longitude) of the IP address:
#Import Geocoder
import Geocoder
#Assign IP address to a variable
ip = geocoder.ip("161.185.160.93")
#Obtain the city
print(ip.city)
#Obtain the coordinates:
print(ip.latlng)
Alternatively, you can also retrieve your own IP address by specifying “me” as the input of geocoder.ip
:
#Assign your own IP address to a variable
ip = geocoder.ip("me")
Geolocate an IP Address on a Map with Folium
Folium is a Python library that allows you to create interactive leaflet maps in Python. It makes it very easy to track an IP address on a map.
Folium Installation
To get started, you’ll need to install Folium using PIP:
pip install folium
You can also install Folium using Conda:
conda install folium -c conda-forge
IP Geolocation on a Map
Now, you can create a map with Folium based on the coordinates obtained earlier. The following code creates a map centered around the IP address’s coordinates and adds a red circle and a marker for visualization:
#Import Folium
import folium
#Extract the coordinates from the 'ip' variable, which was previously obtained
location = ip.latlng
#Create a new Folium map centered around the extracted location coordinates
map = folium.Map(location=location, zoom_start=10)
#Add a red circle marker to the map at the specified 'location'
folium.CircleMarker(location=location, radius=50, color="red").add_to(map)
#Add a standard marker (pin) to the map at the same 'location' coordinates
folium.Marker(location).add_to(map)
#Render the map
map
Export the Map as HTML File
Exporting the map as an HTML file is also possible as follow:
map.save("map.html")
You can then open it in a web browser for example:
Conclusion
This tutorial has shown you how to use the Python as well as Geocoder and Folium libraries to geolocate IP addresses. With this knowledge, you may improve your Python projects and acquire insights from geographic data!