Last modified: Jan 10, 2023 By Alexander Williams
Get Country From Ip in Python
Today, I'm going to show you how to get the Country's name from the IP address using Python.
In this tutorial, we'll use the ipinfo API and the pycountry library.
Get the country's name from IP
We'll write a simple function that gets the country from IP.
import requests
import json
def get(ip):
endpoint = f'https://ipinfo.io/{ip}/json'
response = requests.get(endpoint, verify = True)
if response.status_code != 200:
return 'Status:', response.status_code, 'Problem with the request. Exiting.'
exit()
data = response.json()
return data['country']
How to use it?
my_country = get("196.74.34.70")
print(my_country)
Output
MA
As you can see, we have got MA which is the code of Morocco.
Next, we'll learn how to print the full name of the country.
Print the full name of the country
To print the full name, we need to use the pycountry library.
Install pycountry via pip:
pip install pycountry
Print the full name:
import pycountry
my_country = get("196.74.34.70")
c = pycountry.countries.get(alpha_2=my_country)
print(c.name)
Output
Morocco
Print the official name:
print(c.official_name)
Output
Kingdom of Morocco