Ronnie Atuhaire
Ronnie Atuhaire's Blog 🤓

Ronnie Atuhaire's Blog 🤓

Geo-Locate IPs With Python

Geo-Locate IPs With Python

Ronnie Atuhaire's photo
Ronnie Atuhaire
·Mar 1, 2022·

4 min read

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

  • 🔹 Getting Started
  • 🔹 Geolocation-DB
  • 🔹 IP-API
  • 🔹 Freemium Vs Premium
  • 🔹 Summary
  • 🔹 Conclusion

Hey buddy 👋, welcome here! If you are a usual suspect, glad to see you here again. Today, we shall learn how to get and extract some geo-information from a given IP or a range of IPs.

Geolocating an IP address is a convenient way to identify a user's real-world location.

image.png

Frankly, I don't know why you would want to do this but this information can be useful in custom marketing, web translations, restricting content and maybe tracking down digital footprint.

🔹 Getting Started

We shall majorly be using requests library and JSON for today, you only need to pip install requests if you don't have it.

JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines.

Requests is a Python HTTP library for Humans, not metahumans 🙂.

I chose two API providers for this article, a freemium and a premium one.

🔹 Geolocation-DB

Geolocation IP Databases allow you to determine your website visitor's location. These databases of IP addresses contain the latitude and longitude of a particular IP address.

This particular one helps identify the geographic location of your website's visitors using their free and unlimited geolocation IP API.

The code: I am going to use comments and self-descriptive variables so that you can understand the code easily. Note: I just made up the IP I am going to use through out the examples.

import requests
import json

# IP address to test
ip_address = '200.229.2.90'

# Our Endpoint (API) URL
request_url = f"https://geolocation-db.com/jsonp/{ip_address}"

# Send request and decode the result
response = requests.get(request_url)
result = response.content.decode()

# Clean the returned string so it just contains the JSON String
result = result.split("(")[1].strip(")")

# If you want to write to a file
with open("geo_one.json", "w+") as outfile:
    outfile.write(result)

# Convert this data into dictionary
result  = json.loads(result)
print(result)

The Output

{
    "country_code": "BR",
    "country_name": "Brazil",
    "city": null,
    "postal": null,
    "latitude": -22.8305,
    "longitude": -43.2192,
    "IPv4": "200.229.2.90",
    "state": null
}

From the docs,we can see that we are able to get the following information about a particular IP:

🔹 IP-API

This one seems to be better because it even comes at a fee with analytics, Country Information and other statistics at your disposal.

I tried with their free tier to get its feel and compare it with the free one and indeed there was a difference.

The Code: It will not change much as the previous one, we only need an access key and we must bear the free 1000 API queries that can be made.

Sign up to get your free access key here

import requests
import json

# IP address to test
ip_address = '200.229.2.90'
access = "get_yours 🙂"

# Our Endpoint (API) URL
request_url = f"http://api.ipapi.com/api/{ip_address}?access_key={access}"

# Send request and decode the result
response = requests.get(request_url)
result = response.content.decode()

# If you want to write to a file
with open("geo_two.json", "w+") as outfile:
    outfile.write(result)

# Convert this data into dictionary
result  = json.loads(result)
print(result)

The Output:

{
    "ip": "200.229.2.90",
    "type": "ipv4",
    "continent_code": "NA",
    "continent_name": "North America",
    "country_code": "CR",
    "country_name": "Costa Rica",
    "region_code": "SJ",
    "region_name": "San Jos\u00e9",
    "city": "San Jos\u00e9",
    "zip": "1000",
    "latitude": 9.930000305175781,
    "longitude": -84.0790023803711,
    "location": {
        "geoname_id": 3621849,
        "capital": "San Jos\u00e9",
        "languages": [
            {
                "code": "es",
                "name": "Spanish",
                "native": "Espa\u00f1ol"
            }
        ],
        "country_flag": "https://assets.ipstack.com/flags/cr.svg",
        "country_flag_emoji": "\ud83c\udde8\ud83c\uddf7",
        "country_flag_emoji_unicode": "U+1F1E8 U+1F1F7",
        "calling_code": "506",
        "is_eu": false
    }
}

🔹 Freemium Vs Premium

Do you see the difference above besides the extra metadata ???

For example, Take a look at this map:

image.png

From the map, we can ascertain that Brazil is in South America whereas Costa Rica is in the North! So why did our freemium API IP Geolocator go wrong?

Most of these premium ones offer extended and a little bit accurate data is returned.

GitHub Repo

🔹 Summary

There are lots of GeoIP APIs out there and some are free while others come at a cost. You always have a choice to make in the end.

According to Geo-Targetly, IP-based geolocation services provide 55 per cent to 80 per cent accuracy for a user's region or state. And they provide 50 per cent to 75 per cent accuracy for a user's city.

In practice, the actual accuracy may vary from provider to provider and depending on the location of the device.

Some databases are free and therefore provide minimal information about the IP address and return data exclusively referring to the estimated location.

🔹 Conclusion

Once again, hope you learned something today from my little closet.

Please consider subscribing or following me for related content, especially about Tech, Python & General Programming.

You can show extra love by buying me a coffee to support this free content and I am also open to partnerships, technical writing roles, collaborations and Python-related training or roles.

Buy Ronnie A Coffee 📢 You can also follow me on Twitter : ♥ ♥ Waiting for you! 🙂
 
Share this