Get the location of a device using its IP address [Python]

KUMAR GAUTAMKUMAR GAUTAM
2 min read

Table of contents

To get the location of a device using its IP address, we can use a geolocation service such as ipapi.

Here is an example of how we can use the ipapi service to get the location of a device in Python:

import requests

# Send a GET request to the ipapi service
r = requests.get('https://ipapi.co/{IP_ADDRESS}/json/')

# Get the response data as a Python dictionary
data = r.json()

# Print the location data
print(data)

Below is the sample output generated if we use the IP_ADDRESS address as 49.37.162.15

{'ip': '49.37.162.15', 'network': '49.37.162.0/23', 'version': 'IPv4', 'city': 'Bengaluru', 'region': 'Karnataka', 'region_code': 'KA', 'country': 'IN', 'country_name': 'India', 'country_code': 'IN', 'country_code_iso3': 'IND', 'country_capital': 'New Delhi', 'country_tld': '.in', 'continent_code': 'AS', 'in_eu': False, 'postal': '560001', 'latitude': 12.9634, 'longitude': 77.5855, 'timezone': 'Asia/Kolkata', 'utc_offset': '+0530', 'country_calling_code': '+91', 'currency': 'INR', 'currency_name': 'Rupee', 'languages': 'en-IN,hi,bn,te,mr,ta,ur,gu,kn,ml,or,pa,as,bh,sat,ks,ne,sd,kok,doi,mni,sit,sa,fr,lus,inc', 'country_area': 3287590.0, 'country_population': 1352617328, 'asn': 'AS55836', 'org': 'Reliance Jio Infocomm Limited'}

This example sends a GET request to the ipapi service with the IP address of the device, and retrieves the location data as a Python dictionary. The location data includes the latitude, longitude, city, region, country, and other information about the location.

To use this code, we will need to replace {IP_ADDRESS} with the actual IP address of the device. We can also customize the request to retrieve only specific pieces of information by appending them to the URL as query parameters. For example, we can use the ?city parameter to retrieve only the city of the location.

Although there is no API key required, as per the official website https://ipapi.com/plan, only 1000 lookups are free.

Thanks for reading! I'm a software developer and technical writer. If you enjoyed this post, check out my other articles and do subscribe to my newsletter

2
Subscribe to my newsletter

Read articles from KUMAR GAUTAM directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

KUMAR GAUTAM
KUMAR GAUTAM

Experienced Software Engineer with a demonstrated history of end to end product development and deployment in Python. Skilled in Python Django Framework, RestAPI, Python Dash Framework, Bokeh Data Visualisation, PostgreSQL, MongoDB, Apache Airflow, Deep Learning and Big Data technologies.