IP2Location Python Library

8.11.0 · active · verified Wed Apr 15

This is an IP geolocation library that enables the user to find the country, region, city, latitude and longitude, ZIP code, time zone, ISP, domain name, area code, weather info, mobile info, elevation, usage type, address type and IAB category from an IP address. It supports both IPv4 and IPv6 lookup.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load an IP2Location BIN database file and query geolocation information for an IP address. You must download a database file separately and provide its path.

import IP2Location
import os

# NOTE: You must download an IP2Location BIN database file separately.
# For a free LITE database: https://lite.ip2location.com/ip2location-lite
# Place the .BIN file in a 'data' directory or specify its full path.
DB_PATH = os.path.join("data", "IP2LOCATION-LITE-DB1.BIN") # Replace with your actual database file

# Ensure the database file exists
if not os.path.exists(DB_PATH):
    print(f"Error: IP2Location BIN database not found at {DB_PATH}")
    print("Please download a database from https://lite.ip2location.com/ip2location-lite")
else:
    try:
        # Initialize the IP2Location object with the database file
        # Use 'FILE_IO' (default) or 'SHARED_MEMORY' if your system has enough RAM (IP2Location.IP2LOCATION_SHARED_MEMORY)
        database = IP2Location.IP2Location(DB_PATH)
        
        # Lookup an IP address
        ip_address = "8.8.8.8" # Google Public DNS
        rec = database.get_all(ip_address)

        if rec:
            print(f"IP Address: {ip_address}")
            print(f"Country Code: {rec.country_short}")
            print(f"Country Name: {rec.country_long}")
            print(f"Region Name: {rec.region}")
            print(f"City Name: {rec.city}")
            print(f"Latitude: {rec.latitude}")
            print(f"Longitude: {rec.longitude}")
            print(f"ISP: {rec.isp}")
            # Access other fields like rec.zipcode, rec.timezone, etc.
        else:
            print(f"No data found for IP: {ip_address}")
            print("This might mean your database does not contain this IP range or is outdated.")
    except Exception as e:
        print(f"An error occurred: {e}")
        print("Ensure your BIN database is compatible with the library version and not corrupted.")

view raw JSON →