GeoIP2Fast

1.2.2 · active · verified Thu Apr 16

GeoIP2Fast is a high-performance Python library for GeoIP2 country, city, and ASN lookups, supporting both IPv4 and IPv6. It boasts lookup speeds of less than 0.00003 seconds and utilizes its own data files, updated twice a week with MaxMind GeoLite2 CSV data. The library is pure Python, has no external dependencies, and is currently at version 1.2.2.

Common errors

Warnings

Install

Imports

Quickstart

Initializes the GeoIP2Fast library with a specified data file and performs IP lookups for both IPv4 and IPv6 addresses. It demonstrates how to retrieve country name and ASN details, and handles private IP addresses. It includes error handling for missing data files.

import os
from geoip2fast import GeoIP2Fast

# Ensure data file is present, or download it. For this example, we assume it's in the current directory.
# In a real application, you might use GeoIP2Fast.update_all() or provide a path to an existing file.
# For demonstration, we'll try to use a common data file that might be downloaded separately.
# If not found, a FileNotFoundError will be raised, indicating the data file needs to be obtained.

data_file = os.environ.get('GEOIP2FAST_DATA_FILE', 'geoip2fast-asn-ipv6.dat.gz')

try:
    # Initialize GeoIP2Fast with a specific data file (e.g., with ASN and IPv6 support)
    # The library looks in the current directory and then in the library's package directory.
    geoip = GeoIP2Fast(geoip2fast_data_file=data_file, verbose=False)

    # Lookup an IPv4 address
    ip_v4 = "8.8.8.8"
    result_v4 = geoip.lookup(ip_v4)
    print(f"IPv4 Lookup for {ip_v4}: {result_v4.country_name}, ASN: {result_v4.asn_name}")

    # Lookup an IPv6 address
    ip_v6 = "2001:4860:4860::8888"
    result_v6 = geoip.lookup(ip_v6)
    print(f"IPv6 Lookup for {ip_v6}: {result_v6.country_name}, ASN: {result_v6.asn_name}")

    # Example of a private IP address
    private_ip = "192.168.1.1"
    result_private = geoip.lookup(private_ip)
    print(f"Private IP {private_ip}: is_private={result_private.is_private}")

except FileNotFoundError:
    print(f"Error: GeoIP2Fast data file '{data_file}' not found.")
    print("Please download the necessary .dat.gz file from the GitHub releases (e.g., https://github.com/rabuchaim/geoip2fast/releases/tag/LATEST) and place it in the application directory or specify its path.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →