mmdb-writer Library

0.2.6 · active · verified Fri Apr 17

mmdb-writer is a Python library for creating MaxMind DB (.mmdb) format files, which can be efficiently read by MaxMind's official client libraries in various programming languages. It allows users to associate custom data with IP address ranges (IPv4 and IPv6). The current version is 0.2.6, with updates released periodically, though not on a fixed schedule.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `MMDBWriter`, insert IPv4 and IPv6 networks with various data types, and finalize the database creation. It highlights the use of `insert_network` for single entries and `insert_network_list` for multiple, sharing data. Key parameters like `ip_version`, `database_type`, and `record_size` are explained.

import os
from mmdb_writer import MMDBWriter
from netaddr import IPNetwork # Optional, strings also accepted by insert_network

# Define the output database file
output_file = 'my_ip_database.mmdb'

# Initialize the writer
# ip_version: 4 for IPv4 only, 6 for mixed IPv4/IPv6.
# database_type: An arbitrary string to identify your database.
# record_size: Affects max data size per IP entry (e.g., 24 for ~1.5KB, 32 for ~6KB).
writer = MMDBWriter(
    ip_version=6,
    database_type='Custom-Geo-Database',
    languages=['en', 'es'],
    description={'en': 'My custom IP lookup database', 'es': 'Mi base de datos IP personalizada'},
    record_size=24, # Recommended for many common use cases
    store_ipv4_in_ipv6_format=True # Recommended when ip_version is 6
)

# Insert individual networks with associated data
# Data can be a dictionary, list, string, int, float, or boolean.
writer.insert_network('1.1.1.0/24', {'country': 'US', 'city': 'Exampleville', 'latitude': 34.05, 'longitude': -118.25})
writer.insert_network('2.2.2.0/24', {'country': 'CA', 'isp': 'InternetCorp'})

# Insert a list of networks with the same data
# Can use strings directly or netaddr.IPNetwork objects.
networks_for_region = [
    '3.3.3.0/28',
    IPNetwork('3.3.3.16/28') # Both strings and IPNetwork objects are fine here
]
writer.insert_network_list(networks_for_region, {'country': 'UK', 'continent': 'Europe', 'timezone': 'Europe/London'})

# Insert an IPv6 network
writer.insert_network('2001:db8::/32', {'country': 'DE', 'organization': 'TechSolutions GmbH'})

# Close the writer to finalize and write the database file
writer.close(output_file)

print(f"MMDB database '{output_file}' created successfully.")

# Clean up the created file (uncomment if you want to remove it automatically)
# os.remove(output_file)

view raw JSON →