Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Java reader for the MaxMind DB format

License

NotificationsYou must be signed in to change notification settings

ipinfo/MaxMind-DB-Reader-java

 
 

Repository files navigation

Description

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).

Installation

Maven

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>

Gradle

Add the following to yourbuild.gradle file:

repositories {    mavenCentral()}dependencies {    compile 'com.maxmind.db:maxmind-db:3.2.0'}

Usage

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.

Example

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;        }    }}

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"));// ...}

Caching

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.

Multi-Threaded Use

This API fully supports use in multi-threaded applications. In suchapplications, we suggest creating oneReader object and sharing that amongthreads.

Common Problems

File Lock on Windows

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.

Packaging Database in a JAR

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.

Format

The MaxMind DB format is an open format for quickly mapping IP addresses torecords. Thespecificationis available, as is ourPerl writer for theformat.

Bug Tracker

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.

Requirements

This API requires Java 17 or greater.

Contributing

Patches and pull requests are encouraged. Please include unit tests wheneverpossible.

Versioning

The MaxMind DB Reader API usesSemantic Versioning.

Copyright and License

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

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java98.3%
  • Shell1.7%

[8]ページ先頭

©2009-2025 Movatter.jp