Class IP2Location
This class provides direct access to IP2Location binary database files, supporting both standard file I/O and memory-mapped file access for optimal performance. It is used internally by IP2LocationService.
Memory-Mapped vs Standard I/O
| Mode | Heap Memory | Performance | Use Case |
|---|---|---|---|
| Memory-mapped | Minimal (~1 KB) | Faster random access | Production servers with RAM |
| Standard | Varies with caching | Predictable | Containers, limited memory |
Memory mapping and unmapping
The memory-mapped mode maps the file into a MemorySegment owned by a shared Arena (FileChannel.map(FileChannel.MapMode, long, long, Arena)). Closing the arena in Close() unmaps the file at once, which matters on Windows where a mapped file cannot be replaced or deleted while any mapping exists - the monthly database update replaces the file. The Java 8 to 26 MappedByteBuffer plus sun.misc.Unsafe unmapping of the original implementation is not needed on the Java 25 baseline of this port and is gone with it; the FFM API gives the same immediate release without reflection and without the Unsafe memory-access warning of JDK 24 and later.
Thread Safety
This class is thread-safe. In memory-mapped mode, reads use absolute segment access and require no locking, allowing full concurrency. In standard I/O mode, reads are synchronized on an internal lock since RandomAccessFile is not thread-safe. A lookup that races with Close() in memory-mapped mode gets an IllegalStateException from the closed arena, which IPQuery(String) reports as DATABASE_ERROR.
Database Type Support
Supports all 26 IP2Location database types (DB1-DB26), including both LITE and commercial databases. Field position tables are copied verbatim from the upstream reference implementation (v8.13.0) for accuracy.
IPv6 Special Address Handling
6to4 (2002::/16) and Teredo (2001:0000::/32) addresses are automatically remapped to their embedded IPv4 address for lookup in the IPv4 table, matching the upstream reference behavior.
Usage Example
IP2Location loc = new IP2Location();
try {
loc.Open("/path/to/IP2LOCATION-LITE-DB11.BIN", true); // memory-mapped
IPResult result = loc.IPQuery("8.8.8.8");
if ("OK".equals(result.getStatus())) {
System.out.println("Country: " + result.getCountryShort());
System.out.println("City: " + result.getCity());
}
} finally {
loc.Close();
}
- Author:
- Christopher Mindus
- See Also:
Constructor Details
IP2Location
public IP2Location()
Method Details
Open
- Throws:
IOException
Open
- Throws:
IOException
Close
public void Close()IPQuery
getDatabaseType
public int getDatabaseType()getDatabaseVersion
getDatabaseDate
isLoaded
public boolean isLoaded()hasIPv6Support
public boolean hasIPv6Support()getDatabasePath