- Notifications
You must be signed in to change notification settings - Fork48
Java reader for the MaxMind DB format
License
maxmind/MaxMind-DB-Reader-java
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This is the Java API for reading MaxMind DB files. MaxMind DB is a binary fileformat that stores data indexed by IP address subnets (IPv4 or IPv6).
We recommend installing this package withMaven.To do this, add the dependency to your pom.xml:
<dependency> <groupId>com.maxmind.db</groupId> <artifactId>maxmind-db</artifactId> <version>3.2.0</version> </dependency>
Add the following to yourbuild.gradle file:
repositories { mavenCentral()}dependencies { compile 'com.maxmind.db:maxmind-db:3.2.0'}Note: For accessing MaxMind GeoIP2 databases, we generally recommend usingtheGeoIP2 Java API rather than usingthis package directly.
To use the API, you must first create aReader object. The constructor forthe reader object takes aFile representing your MaxMind DB. Optionally youmay pass a second parameter with aFileMode with a value ofMEMORY_MAP orMEMORY. The default mode isMEMORY_MAP, which maps the file to virtualmemory. This often provides performance comparable to loading the file intoreal memory withMEMORY.
To look up an IP address, pass the address as anInetAddress to thegetmethod onReader, along with the class of the object you want todeserialize into. This method will create an instance of the class andpopulate it. See examples below.
We recommend reusing theReader object rather than creating a new one foreach lookup. The creation of this object is relatively expensive as it mustread in metadata for the file.
importcom.maxmind.db.MaxMindDbConstructor;importcom.maxmind.db.MaxMindDbParameter;importcom.maxmind.db.Reader;importcom.maxmind.db.DatabaseRecord;importjava.io.File;importjava.io.IOException;importjava.net.InetAddress;publicclassLookup {publicstaticvoidmain(String[]args)throwsIOException {Filedatabase =newFile("/path/to/database/GeoIP2-City.mmdb");try (Readerreader =newReader(database)) {InetAddressaddress =InetAddress.getByName("24.24.24.24");// get() returns just the data for the associated recordLookupResultresult =reader.get(address,LookupResult.class);System.out.println(result.getCountry().getIsoCode());// getRecord() returns a DatabaseRecord class that contains both// the data for the record and associated metadata.DatabaseRecord<LookupResult>record =reader.getRecord(address,LookupResult.class);System.out.println(record.getData().getCountry().getIsoCode());System.out.println(record.getNetwork()); } }publicstaticclassLookupResult {privatefinalCountrycountry;@MaxMindDbConstructorpublicLookupResult (@MaxMindDbParameter(name="country")Countrycountry ) {this.country =country; }publicCountrygetCountry() {returnthis.country; } }publicstaticclassCountry {privatefinalStringisoCode;@MaxMindDbConstructorpublicCountry (@MaxMindDbParameter(name="iso_code")StringisoCode ) {this.isoCode =isoCode; }publicStringgetIsoCode() {returnthis.isoCode; } }}
- Preferred: annotate a constructor with
@MaxMindDbConstructorand itsparameters with@MaxMindDbParameter(name = "..."). - Records: if no constructor is annotated, the canonical record constructor isused automatically. Record component names are used as field names.
- Classes with a single public constructor: if no constructor is annotated,that constructor is used automatically.
- Unannotated parameters: when a parameter is not annotated, the reader fallsback to the parameter name. For records, this is the component name; forclasses, this is the Java parameter name. To use Java parameter names atruntime, compile your model classes with the
-parametersflag (Maven:maven-compiler-pluginwith<parameters>true</parameters>).If Java parameter names are unavailable (no-parameters) and there is no@MaxMindDbParameterannotation, the reader throws aParameterNotFoundExceptionwith guidance.
Defaults for missing values
Provide a default with
@MaxMindDbParameter(name = "...", useDefault = true, defaultValue = "...").Supports primitives, boxed types, and
String. IfdefaultValueis emptyanduseDefaultis true, Java defaults are used (0, false, 0.0, emptystring).Example:
@MaxMindDbConstructorExample(@MaxMindDbParameter(name ="count",useDefault =true,defaultValue ="0")intcount,@MaxMindDbParameter(name ="enabled",useDefault =true,defaultValue ="true" )booleanenabled) { }
Lookup context injection
- Use
@MaxMindDbIpAddressto inject the IP address being decoded.Supported parameter types areInetAddressandString. - Use
@MaxMindDbNetworkto inject the network of the resulting record.Supported parameter types areNetworkandString. - Context annotations cannot be combined with
@MaxMindDbParameteron the sameconstructor argument. Values are populated for every lookup without beingcached between different IPs.
Custom deserialization
Use
@MaxMindDbCreatorto mark a static factory method or constructor thatshould be used for custom deserialization of a type from a MaxMind DB file.This annotation is similar to Jackson's
@JsonCreatorand is useful fortypes that need custom deserialization logic, such as enums with non-standardstring representations or types that require special initialization.The annotation can be applied to both constructors and static factory methods.
Example with an enum:
publicenumConnectionType {DIALUP("Dialup"),CABLE_DSL("Cable/DSL");privatefinalStringname;ConnectionType(Stringname) {this.name =name; }@MaxMindDbCreatorpublicstaticConnectionTypefromString(Strings) {returnswitch (s) {case"Dialup" ->DIALUP;case"Cable/DSL" ->CABLE_DSL;default ->null; }; }}
You can also use the reader object to iterate over the database.Thereader.networks() andreader.networksWithin() methods canbe used for this purpose.
Readerreader =newReader(file);Networksnetworks =reader.networks(Map.class);while(networks.hasNext()) {DatabaseRecord<Map<String,String>>iteration =networks.next();// Get the data.Map<String,String>data =iteration.getData();// The IP AddressInetAddressipAddress =InetAddress.getByName(data.get("ip"));// ...}
The database API supports pluggable caching (by default, no caching isperformed). A simple implementation is provided bycom.maxmind.db.CHMCache.Using this cache, lookup performance is significantly improved at the cost ofa small (~2MB) memory overhead.
Usage:
Readerreader =newReader(database,newCHMCache());
Please note that the cache will hold references to the objects createdduring the lookup. If you mutate the objects, the mutated objects will bereturned from the cache on subsequent lookups.
This API fully supports use in multi-threaded applications. In suchapplications, we suggest creating oneReader object and sharing that amongthreads.
By default, this API uses theMEMORY_MAP mode, which memory maps the file.On Windows, this may create an exclusive lock on the file that prevents itfrom being renamed or deleted. Due to the implementation of memory mapping inJava, this lock will not be released when theDatabaseReader is closed; itwill only be released when the object and theMappedByteBuffer it uses aregarbage collected. Older JVM versions may also not release the lock on exit.
To work around this problem, use theMEMORY mode or try upgrading your JVMversion. You may also callSystem.gc() after dereferencing theDatabaseReader object to encourage the JVM to garbage collect sooner.
If you are packaging the database file as a resource in a JAR file usingMaven, you mustdisable binary file filtering.Failure to do so will result inInvalidDatabaseException exceptions beingthrown when querying the database.
The MaxMind DB format is an open format for quickly mapping IP addresses torecords. Thespecificationis available, as is ourPerl writer for theformat.
Please report all issues with this code using theGitHub issuetracker.
If you are having an issue with a MaxMind database or service that is notspecific to this reader, pleasecontact MaxMind support.
This API requires Java 17 or greater.
Patches and pull requests are encouraged. Please include unit tests wheneverpossible.
The MaxMind DB Reader API usesSemantic Versioning.
This software is Copyright (c) 2014-2025 by MaxMind, Inc.
This is free software, licensed under the Apache License, Version 2.0.
About
Java reader for the MaxMind DB format
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.