To read an MMDB file, open it once with an MMDB reader library and pass each IP address to the reader's lookup call. You get back the record for the IP range that holds the address, or nothing when no range does. An MMDB file is binary, so a text editor won't show you anything useful; the reader walks a search tree inside the file to find each address.
Here are four programs, in Python, Go, Node.js, and Java, that read IPGeolocation.io's location database and print the same results in every language. Each one handles the three outcomes every lookup has: a record, no record, and input that isn't an IP address. All four were run against our free sample files on October 27, 2026.
TL;DR
To read an MMDB file in Python, Go, Node.js, or Java, install the reader for your language and keep one reader open for the life of your process. In IPGeolocation.io location records, numbers are stored as strings, place names are keyed by language code, and no field is ever null.
- Python 3.9+:
pip install ipgeolocation-mmdb-reader, thenIPGeolocationMMDBReader(path), imported from.lookup(ip) ipgeo_mmdb_reader. - Go 1.26+: the reader in the Go section opens the file with
Open()and looks up anetip.AddrwithLookup(). - Node.js 16+:
npm install ipgeolocation-mmdb-reader, thennew IPGeolocationMMDBReader(path)..lookup(ip) - Java 17+: add
io, then.ipgeolocation:ipgeolocation-mmdb-reader:1 .0 .0 new IPGeolocationMMDBReader(path)..lookup(ip)
Get a file and a runtime
You need an MMDB file and one of four runtimes. Check these before you start:
- An MMDB file. Customers get the latest release from the static download link we send when they subscribe. To try this without a subscription, download the free MMDB sample from the IP to Location product page, which offers both a Geo Standard and a Geo Advanced sample. Each download is a ZIP archive holding
db-ip-location.mmdb, aREADME.md, and achecksum.txt. - An unzipped, checked file. Unzip the archive and run
sha256sum -c checksumin the folder (.txt shasum -a 256 -c checksumon macOS); every line should end in.txt OK. Subscription releases also come with a signature file, and the IP to Location database documentation gives the OpenSSL command that checks it. - A runtime at the minimum version: Python 3.9, Go 1.26, Node.js 16, or Java 17 with Maven or Gradle. We ran the programs on Python 3.9.25 and 3.10.12, Go 1.26.10, Node.js 16.20.2 and 22.23.2, and Java 17.0.21 with Maven 3.9.9.
Every program reads the file path from the IPGEO_MMDB_PATH environment variable and falls back to db-ip-location.mmdb in the current folder. With no arguments, each one looks up the same four inputs: 217.154.81.50, a hosting provider's IPv4 address; 2404:f801:8028::1, an IPv6 address in a large company's network; 192.0.2.1, from a range set aside for documentation, so no file has a record for it; and not-an-ip, to show what bad input does.
What one lookup returns
A lookup in our location file returns one nested record per IP range. Here is the record for 217.154.81.50 from the Geo Advanced sample, trimmed to the fields the programs print plus a few that show the shape:
json
{
"location": {
"accuracy_radius": "7.771",
"city": { "name": { "en": "Frankfurt" } },
"confidence": "high",
"coordinates": { "latitude": "50.11208", "longitude": "8.68341" },
"country": {
"code2": "DE",
"currency": { "code": "EUR", "name": { "en": "Euro" }, "symbol": "€" },
"name": { "de": "Deutschland", "en": "Germany", "es": "Alemania", "fr": "Allemagne" }
},
"state": { "code": "DE-HE", "name": { "de": "Hessen", "en": "Hesse" } },
"zipcode": "60311"
},
"time_zone": "Europe/Berlin"
}
Place names come keyed by language code. In the full record, every place name (country, continent, capital, state, district, and city) carries twelve keys: cs, de, en, es, fa, fr, it, ja, ko, pt, ru, and zh. So ["name"]["de"] gets you "Deutschland" instead of "Germany", and a key is present even when its translation is empty. The currency name is the one exception, with English only. The programs read the en keys.
Numbers arrive as strings. latitude, longitude, accuracy_radius, and geoname_id are all text, so convert them before you compare, sort, or calculate with them. Every program converts accuracy_radius to a number before rounding it, and confidence holds high, medium, or low.
The two editions don't hold the same fields. A Geo Advanced record adds accuracy_radius, confidence, dma_code, and connection_type, and a Geo Standard record has none of the four. Apart from those, our field reference promises that every field in an edition's schema is always present and never null (an empty value is an empty string), so you can read the shared fields directly. Only the four Advanced-only fields need a check, and every program does that check, which is why the same code reads both Geo Standard and Geo Advanced files.
Read an MMDB file in Python
Our Python package, ipgeolocation-mmdb-reader, is pure Python with no dependencies. It memory-maps the file, so opening even a large database doesn't copy it into your process. Install it:
bash
pip install ipgeolocation-mmdb-readerOn a Linux distribution that manages the system Python (pip stops with "externally-managed-environment"), run python3 -m venv and . first. The import name differs from the package name: you install ipgeolocation-mmdb-reader and import ipgeo_mmdb_reader. Save this as read_mmdb.py:
python
"""Look up IP addresses in an IPGeolocation.io MMDB file."""
import os
import sys
from datetime import datetime, timezone
from ipgeo_mmdb_reader import IPGeolocationMMDBReader, MMDBError, MetadataError
DB_PATH = os.environ.get("IPGEO_MMDB_PATH", "db-ip-location.mmdb")
def describe(record):
"""Summarize one location record. Geo Standard files have no accuracy radius or confidence."""
location = record["location"]
country = location["country"]
city = location["city"]["name"]["en"] or "(no city)"
coords = location["coordinates"]
line = (f'{country["code2"]} {country["name"]["en"]}, {city} | {record["time_zone"]} | '
f'{coords["latitude"]}, {coords["longitude"]}')
radius = location.get("accuracy_radius", "") # missing in Geo Standard, so .get()
if radius:
# Numbers arrive as strings, so convert before you compare or calculate.
line += f' | within {float(radius):.0f} km ({location["confidence"]} confidence)'
return line
def main(ips):
try:
reader = IPGeolocationMMDBReader(DB_PATH)
except FileNotFoundError:
sys.exit(f"No file at {DB_PATH}. Unzip the archive and point IPGEO_MMDB_PATH at the .mmdb file.")
except MetadataError as err:
sys.exit(f"{DB_PATH} is not an MMDB file: {err}")
except OSError as err: # permissions, unreadable disk, and the like
sys.exit(f"{DB_PATH} could not be opened: {err}")
with reader: # closes the file when the block ends
meta = reader.get_metadata()
built = datetime.fromtimestamp(meta["build_epoch"], tz=timezone.utc).date()
print(f"Opened {DB_PATH}, built {built}")
for ip in ips:
try:
record = reader.lookup(ip)
except MMDBError as err: # input that isn't an IP address
print(f"{ip}: skipped ({err})")
continue
print(f"{ip}: {describe(record) if record else 'no record'}")
if __name__ == "__main__":
main(sys.argv[1:] or ["217.154.81.50", "2404:f801:8028::1", "192.0.2.1", "not-an-ip"])lookup() returns a dict, or None when no range covers the address, and it raises MMDBError for input it can't parse. The build date comes from the file's own metadata, which tells you which release you're running. Run it with python3 read_mmdb; with the Geo Advanced sample in the folder, it prints:
text
Opened db-ip-location.mmdb, built 2026-10-26
217.154.81.50: DE Germany, Frankfurt | Europe/Berlin | 50.11208, 8.68341 | within 8 km (high confidence)
2404:f801:8028::1: IN India, Hyderabad | Asia/Kolkata | 17.35084, 78.45368 | within 4 km (high confidence)
192.0.2.1: no record
not-an-ip: skipped (Invalid IP address)Your build date will differ, and a Geo Standard file prints the same lines without the "within ... km" part. The usual first failure is pointing the program at the ZIP archive instead of the file inside it; the reader rejects it with MetadataError ("metadata marker not found"), and the program says the file isn't an MMDB file.
The reader caches each record it decodes and hands back the same dict on the next lookup of that range. Treat records as read-only, and copy one (copy) before you change it, or the change shows up in later lookups.
Read an MMDB file in Go
In Go, the program uses one reader module. It memory-maps the file, needs Go 1.26 or later, and is safe to share across goroutines. Set up a module and add the reader:
bash
go mod init example.com/ipgeo-lookup
go get github.com/oschwald/maxminddb-golang/v2@v2.8.0Save this as main.go:
go
// Command ipgeo-lookup looks up IP addresses in an IPGeolocation.io MMDB file.
package main
import (
"fmt"
"log"
"net/netip"
"os"
"strconv"
"time"
mmdb "github.com/oschwald/maxminddb-golang/v2"
)
// field reads one string from a record by its path. A path the file doesn't
// have (accuracy_radius in Geo Standard, say) leaves the value empty.
func field(res mmdb.Result, path ...any) (string, error) {
var v string
err := res.DecodePath(&v, path...)
return v, err
}
func describe(db *mmdb.Reader, raw string) (string, error) {
addr, err := netip.ParseAddr(raw)
if err != nil {
return "", fmt.Errorf("invalid IP address")
}
res := db.Lookup(addr)
if err := res.Err(); err != nil {
return "", err
}
if !res.Found() {
return "no record", nil
}
paths := [][]any{
{"location", "country", "code2"},
{"location", "country", "name", "en"},
{"location", "city", "name", "en"},
{"time_zone"},
{"location", "coordinates", "latitude"},
{"location", "coordinates", "longitude"},
{"location", "accuracy_radius"},
{"location", "confidence"},
}
v := make([]string, len(paths))
for i, p := range paths {
if v[i], err = field(res, p...); err != nil {
return "", fmt.Errorf("decode %v: %w", p, err)
}
}
code, country, city, tz, lat, lon, radius, confidence := v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]
if city == "" {
city = "(no city)"
}
line := fmt.Sprintf("%s %s, %s | %s | %s, %s", code, country, city, tz, lat, lon)
if radius != "" {
// Numbers arrive as strings, so parse before you compare or calculate.
if km, err := strconv.ParseFloat(radius, 64); err == nil {
line += fmt.Sprintf(" | within %.0f km (%s confidence)", km, confidence)
}
}
return line, nil
}
func main() {
path := os.Getenv("IPGEO_MMDB_PATH")
if path == "" {
path = "db-ip-location.mmdb"
}
db, err := mmdb.Open(path) // memory-maps the file; open once and share
if err != nil {
log.Fatalf("open %s: %v", path, err)
}
defer db.Close()
built := time.Unix(int64(db.Metadata.BuildEpoch), 0).UTC().Format("2006-01-02")
fmt.Printf("Opened %s, built %s\n", path, built)
ips := os.Args[1:]
if len(ips) == 0 {
ips = []string{"217.154.81.50", "2404:f801:8028::1", "192.0.2.1", "not-an-ip"}
}
for _, ip := range ips {
line, err := describe(db, ip)
if err != nil {
fmt.Printf("%s: skipped (%v)\n", ip, err)
continue
}
fmt.Printf("%s: %s\n", ip, line)
}
}Rather than decode the whole record into a struct, the program reads each field by its path with DecodePath, which leaves the value empty when a path doesn't exist. That's how one binary reads both editions. Parsing the address with netip.ParseAddr first turns bad input into an error you can report before any lookup. Run it with go run .:
text
Opened db-ip-location.mmdb, built 2026-10-26
217.154.81.50: DE Germany, Frankfurt | Europe/Berlin | 50.11208, 8.68341 | within 8 km (high confidence)
2404:f801:8028::1: IN India, Hyderabad | Asia/Kolkata | 17.35084, 78.45368 | within 4 km (high confidence)
192.0.2.1: no record
not-an-ip: skipped (invalid IP address)If Open fails with an error saying the file isn't a valid database, you've pointed it at the ZIP archive rather than the unzipped .mmdb file.
Read an MMDB file in Node.js
For Node.js, our ipgeolocation-mmdb-reader package has no runtime dependencies and ships TypeScript declarations. Install it:
bash
npm install ipgeolocation-mmdb-readerSave this as read-mmdb.js (or as read-mmdb.cjs if your package.json sets "type": "module", since the program uses require):
javascript
// Look up IP addresses in an IPGeolocation.io MMDB file.
"use strict";
const {
IPGeolocationMMDBReader,
MMDBError,
MetadataError,
} = require("ipgeolocation-mmdb-reader");
const DB_PATH = process.env.IPGEO_MMDB_PATH || "db-ip-location.mmdb";
function describe(record) {
const location = record.location;
const country = location.country;
const city = location.city.name.en || "(no city)";
const { latitude, longitude } = location.coordinates;
let line = `${country.code2} ${country.name.en}, ${city} | ${record.time_zone} | ${latitude}, ${longitude}`;
const radius = location.accuracy_radius; // undefined in Geo Standard files
if (radius) {
// Numbers arrive as strings, so convert before you compare or calculate.
line += ` | within ${Math.round(Number(radius))} km (${location.confidence} confidence)`;
}
return line;
}
function main(ips) {
let reader;
try {
reader = new IPGeolocationMMDBReader(DB_PATH);
} catch (err) {
// A missing file throws a plain Error; a file that isn't MMDB throws MetadataError.
const reason = err instanceof MetadataError ? "is not an MMDB file" : "could not be opened";
console.error(`${DB_PATH} ${reason}: ${err.message}`);
process.exitCode = 1;
return;
}
try {
const meta = reader.getMetadata();
const built = new Date(Number(meta.build_epoch) * 1000).toISOString().slice(0, 10);
console.log(`Opened ${DB_PATH}, built ${built}`);
for (const ip of ips) {
try {
const record = reader.lookup(ip);
console.log(`${ip}: ${record ? describe(record) : "no record"}`);
} catch (err) {
if (!(err instanceof MMDBError)) throw err;
console.log(`${ip}: skipped (${err.message})`);
}
}
} finally {
reader.close();
}
}
const args = process.argv.slice(2);
main(args.length ? args : ["217.154.81.50", "2404:f801:8028::1", "192.0.2.1", "not-an-ip"]);lookup() returns the record or null, and it throws MMDBError for input it can't parse; the program rethrows anything else so a real bug doesn't pass as bad input. Run it with node read-mmdb.js:
text
Opened db-ip-location.mmdb, built 2026-10-26
217.154.81.50: DE Germany, Frankfurt | Europe/Berlin | 50.11208, 8.68341 | within 8 km (high confidence)
2404:f801:8028::1: IN India, Hyderabad | Asia/Kolkata | 17.35084, 78.45368 | within 4 km (high confidence)
192.0.2.1: no record
not-an-ip: skipped (Invalid IP address)For large databases, use the Python, Go, or Java reader.
Open the reader once when your process starts and reuse it for every lookup, rather than opening one per request or per worker thread. Records also come back as shared objects, so copy one (JSON works, since every value is a string or an object) before you change it.
Read an MMDB file in Java
In Java, our ipgeolocation-mmdb-reader package needs Java 17 or later and has no runtime dependencies. It memory-maps the file by default and is safe to share across threads. Add it to your pom.xml:
xml
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>ipgeo-lookup</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.ipgeolocation</groupId>
<artifactId>ipgeolocation-mmdb-reader</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>With Gradle, the same dependency is one line: implementation 'io. Save the program as src/:
java
package com.example;
import io.ipgeolocation.mmdb.IPGeolocationMMDBReader;
import io.ipgeolocation.mmdb.MMDBException;
import io.ipgeolocation.mmdb.MetadataException;
import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
/** Looks up IP addresses in an IPGeolocation.io MMDB file. */
public final class ReadMmdb {
/** Walks a path of map keys; returns "" when a key is missing (accuracy_radius in Geo Standard, say). */
static String text(Map<String, Object> record, String... path) {
Object node = record;
for (String key : path) {
if (!(node instanceof Map<?, ?> map)) {
return "";
}
node = map.get(key);
}
return node == null ? "" : node.toString();
}
static String describe(Map<String, Object> r) {
String city = text(r, "location", "city", "name", "en");
String line = String.format("%s %s, %s | %s | %s, %s",
text(r, "location", "country", "code2"),
text(r, "location", "country", "name", "en"),
city.isEmpty() ? "(no city)" : city,
text(r, "time_zone"),
text(r, "location", "coordinates", "latitude"),
text(r, "location", "coordinates", "longitude"));
String radius = text(r, "location", "accuracy_radius");
if (!radius.isEmpty()) {
// Numbers arrive as strings, so parse before you compare or calculate.
line += String.format(" | within %.0f km (%s confidence)",
Double.parseDouble(radius), text(r, "location", "confidence"));
}
return line;
}
public static void main(String[] args) {
String path = System.getenv().getOrDefault("IPGEO_MMDB_PATH", "db-ip-location.mmdb");
List<String> ips = args.length > 0 ? List.of(args)
: List.of("217.154.81.50", "2404:f801:8028::1", "192.0.2.1", "not-an-ip");
// One reader per file, shared by every thread; try-with-resources releases the memory map.
try (IPGeolocationMMDBReader reader = new IPGeolocationMMDBReader(path)) {
String built = Instant.ofEpochSecond(reader.getBuildEpoch()).atZone(ZoneOffset.UTC).toLocalDate().toString();
System.out.println("Opened " + path + ", built " + built);
for (String ip : ips) {
try {
Map<String, Object> record = reader.lookup(ip);
System.out.println(ip + ": " + (record == null ? "no record" : describe(record)));
} catch (MMDBException e) { // input that isn't an IP address
System.out.println(ip + ": skipped (" + e.getMessage() + ")");
}
}
} catch (NoSuchFileException e) {
System.err.println("No file at " + path + ". Unzip the archive and point IPGEO_MMDB_PATH at the .mmdb file.");
System.exit(1);
} catch (MetadataException e) {
System.err.println(path + " is not an MMDB file: " + e.getMessage());
System.exit(1);
} catch (IOException e) {
System.err.println(path + " could not be opened: " + e.getMessage());
System.exit(1);
}
}
}Records come back as unmodifiable Map<String, Object> values, and the text() helper walks a path through them, returning an empty string where a key is missing. The reader's database and address errors extend the unchecked MMDBException; opening a file can still throw the checked IOException, which the try block handles. Run it with Maven, which fetches its exec plugin on the first run, so the pom.xml doesn't need to declare it:
bash
mvn -q compile exec:java -Dexec.mainClass=com.example.ReadMmdbtext
Opened db-ip-location.mmdb, built 2026-10-26
217.154.81.50: DE Germany, Frankfurt | Europe/Berlin | 50.11208, 8.68341 | within 8 km (high confidence)
2404:f801:8028::1: IN India, Hyderabad | Asia/Kolkata | 17.35084, 78.45368 | within 4 km (high confidence)
192.0.2.1: no record
not-an-ip: skipped (Invalid IP address: not-an-ip)If Maven can't find db-ip-location.mmdb, it's looking in the project folder; set IPGEO_MMDB_PATH to the file's full path. The pom.xml sets maven to 17, so a build on an older JDK stops before the program runs.
Run lookups in production
The four programs open the file, run a few lookups, and exit. A service that answers lookups all day needs three more habits.
1. Open the reader once and share it
Opening parses the file's metadata, so do it at startup and reuse the reader for every request. The Go and Java readers are documented as safe across goroutines and threads.
2. Treat records as read-only
The Python and Node.js readers hand back cached objects, and the Java reader returns unmodifiable maps. Copy a record before you add fields to it.
3. Swap in new releases without stopping lookups
IPGeolocation.io ships new releases daily or weekly, depending on your plan, with the same file name every time. Save each new release under a new name, open a new reader on it, and send new lookups to the new reader. Once the lookups already running on the old reader finish, close it and delete the old file: the Go and Java readers both say Close must not run while other calls on the reader are in flight. Never overwrite a file a reader has open: the memory-mapping readers (Python, Go, and Java) read the file in place, so a rewrite under them can return wrong records or crash the process.

Read our other MMDB databases
The same open-and-lookup code reads our other MMDB databases; only the record keys you read change. The IP Security, IP to ASN, IP to Company, and IP Abuse Contact documentation pages each list their MMDB field paths, and our database formats article names the file inside each archive. If you'd rather query MMDB data with SQL than with code, our DuckDB integration guide shows how.
Frequently asked questions
An MMDB file is a binary file format built for IP lookups. It maps IP ranges to records and stores them in a search tree, so a reader finds the record for an address by walking the bits of that address instead of scanning the file. IPGeolocation.io ships its location, security, ASN, company, and abuse contact databases as MMDB files.
Use mmdbio, our command-line tool for MMDB files. mmdbio read --db db-ip-location prints the record as JSON, and the tool also exports records, shows a file's schema, and validates a file before you deploy it. It reads any MMDB file, not only IPGeolocation.io's.
Yes. IPGeolocation.io offers free sample files for the Geo Standard and Geo Advanced location databases on the IP to Location product page. Each sample is a ZIP archive with db-ip-location.mmdb, a README, and a checksum file, and it holds a subset of the full database's IP ranges.
You don't need to with IPGeolocation.io data: every lookup database we ship in MMDB also ships as CSV, built from the same data. To turn records from an MMDB file into another format, mmdbio's export command writes them out as JSON, or as a plain list of CIDR ranges.
Get the full IPGeolocation.io databases
The samples hold a subset of our location data; a subscription gets you the full files. IPGeolocation.io ships IP geolocation with time zone, security risk signals (VPN, proxy, Tor, and bot detection with a threat score), ASN, company, and abuse contact data as MMDB databases, each also available as CSV, with IPv4 and IPv6 ranges in one file. Every release arrives through static download links that never change, with a checksum file and a signature you verify against our public key.
Databases are sold by quote, as single databases, ready-made bundles, or custom builds, with daily or weekly downloads. Compare the tiers on our database pricing page and request a quote there. If you'd rather call an API per lookup than host files, our guide to choosing between an IP geolocation API and a database walks through that decision.







