java.lang.Object
com.maxmind.geoip.LookupService
Provides a lookup service for information based on an IP address. The location of a database file is supplied when creating a lookup service instance. The edition of the database determines what information is available about an IP address. See the DatabaseInfo class for further details.
The following code snippet demonstrates looking up the country that an IP address is from:
// First, create a LookupService instance with the location of the database.
LookupService lookupService = new LookupService("c:\\geoip.dat");
// Assume we have a String ipAddress (in dot-decimal form).
Country country = lookupService.getCountry(ipAddress);
System.out.println("The country is: " + country.getName());
System.out.println("The country code is: " + country.getCode());
In general, a single LookupService instance should be created and then reused repeatedly.Tip: Those deploying the GeoIP API as part of a web application may find it difficult to pass in a File to create the lookup service, as the location of the database may vary per deployment or may even be part of the web-application. In this case, the database should be added to the classpath of the web-app. For example, by putting it into the WEB-INF/classes directory of the web application. The following code snippet demonstrates how to create a LookupService using a database that can be found on the classpath:
String fileName = getClass().getResource("/GeoIP.dat").toExternalForm()
.substring(6);
LookupService lookupService = new LookupService(fileName);
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate classWalks the search tree once, writing every address that maps to one segment.Field Summary
Modifier and TypeFieldDescriptionprivate static final intCountry table offset for Canadian province records.private static final CharsetCharset used for the database strings.private final CharsetDecoderDecoder for the database strings.private static final intDatabase offset where country records begin.private static final String[]Country codes indexed by the database.private static final String[]Country names indexed by the database.private static final intLongest database info field read.private final FileThe GeoIP database file.private DatabaseInfoInformation about the database.private int[]Segment start offsets in the database.private byteThe database type.private byte[]The whole database, when memory-mapped mode is off.private intDatabase type flags for this file.private RandomAccessFileRandom access handle on the database file.private static final intSize of the FIPS country code range.private static final intScratch buffer size for a full record.static final intNetSpeed edition: the connection is cable or DSL.static final intCache flag: stat the database file on each lookup and reload it if it changed.static final intNetSpeed edition: the connection is corporate or faster.static final intNetSpeed edition: the connection is dialup or slower.static final intCache flag: hold the search index in RAM while still reading records from disk.static final intCache flag: load the whole database into RAM and read records from it.static final intNo cache: every node visit is a disk read.static final intNetSpeed edition: the ISP's connection speed is not classified.private byte[]Cache of the first-level index records.private intNetmask of the last lookup.private static final intLongest org record read.private static final intLongest record length supported.private longModification time of the database file.private static final intRecord length for org databases, in bytes.private intRecord length in bits, from the file.private static final intRecord length for segment regions, in bytes.private static final intRecord length for standard databases, in bytes.private static final intState record start in revision 0 databases.private static final intState record start in revision 1 databases.private static final intLongest structure info field read.private final CountryCountry returned when nothing matches.private static final intCountry table offset for US state records.private static final intCountry table offset for world region records.Constructor Summary
ConstructorsConstructorDescriptionLookupService(File databaseFile) Create a new lookup service using the specified database file.LookupService(File databaseFile, int options) Create a new lookup service using the specified database file.LookupService(String databaseFile) Create a new lookup service using the specified database file.LookupService(String databaseFile, int options) Create a new lookup service using the specified database file.Method Summary
Modifier and TypeMethodDescription(package private) voidVoidprivate static longbytesToLong(byte[] address) Returns the long version of an IP address given an InetAddress object.voidclose()Closes the lookup service.voidcountryToIP(String country, Writer out) I2P - Write all IPv4 address ranges for the given country to out.The ISO country codes the loaded database can resolve, as a copy of its internal code table.The country names the loaded database can resolve, as a copy of its internal name table.getCountry(long ipAddress) Returns the country the IP address is in.getCountry(String ipAddress) Returns the country the IP address is in.getCountry(InetAddress ipAddress) Returns the country the IP address is in.getCountryV6(String ipAddress) Returns the country the IP address is in.getCountryV6(InetAddress addr) Returns the country the IP address is in.Returns information about the database.intgetID(long ipAddress) Looks up the database record ID covering the given IP address.intLooks up the database record ID covering the given IP address.intgetID(InetAddress ipAddress) Looks up the database record ID covering the given IP address.getLocation(long ipnum) Looks up the city record for an IPv4 address.getLocation(String str) Looks up the city record for an IPv4 address.getLocation(InetAddress addr) Looks up the city record for an IPv4 address.getLocationV6(String str) Looks up the city record for an IPv6 address.getLocationV6(InetAddress addr) Looks up the city record for an IPv6 address.getOrg(long ipnum) Looks up the owning organisation for an IPv4 address.Looks up the owning organisation for an IPv4 address.getOrg(InetAddress addr) Looks up the owning organisation for an IPv4 address.Looks up the owning organisation for an IPv6 address.getOrgV6(InetAddress addr) Looks up the owning organisation for an IPv6 address.getRegion(long ipnum) Looks up the region record for an IPv4 address.Looks up the region record for an IPv4 address.getRegion(InetAddress addr) Looks up the region record for an IPv4 address.private voidinit()Reads meta-data from the database file.intReturns the prefix length that the last search stopped at.voidnetmask(int nm) Sets the prefix length thatlast_netmask()reports.private static floatreadAngle(ByteBuffer buffer) Reads a latitude or longitude value from the buffer.private LocationreadCityRecord(int seekCountry) Reads the city record for a country seek position.private static intreadMetroAreaCombo(ByteBuffer buffer) Reads the combined metro area code from the buffer.private voidreadNode(byte[] buf, int[] x, int offset) Reads one node's two child offsets into x.private StringreadOrgRecord(int seekOrg) Reads the organization name for a seek position.private ByteBufferreadRecordBuf(int seek, int maxLength) Reads a record's bytes into a buffer.private StringreadString(ByteBuffer buffer) Reads a NUL-terminated string from the buffer.private intseekCountry(long ipAddress) Finds the country index value given an IP address.private intseekCountryV6(InetAddress addr) Finds the country index value given an IPv6 address.private static intunsignedByteToInt(byte b) Converts a byte to its unsigned value.
Field Details
file
Random access handle on the database file.databaseFile
The GeoIP database file.databaseInfo
Information about the database.charset
Charset used for the database strings.charsetDecoder
Decoder for the database strings.databaseType
private byte databaseTypeThe database type. Default is the country edition.databaseSegments
private int[] databaseSegmentsSegment start offsets in the database.recordLength
private int recordLengthRecord length in bits, from the file.dboptions
private int dboptionsDatabase type flags for this file.dbbuffer
private byte[] dbbufferThe whole database, when memory-mapped mode is off.index_cache
private byte[] index_cacheCache of the first-level index records.mtime
private long mtimeModification time of the database file.last_netmask
private int last_netmaskNetmask of the last lookup.US_OFFSET
private static final int US_OFFSETCountry table offset for US state records.- See Also:
CANADA_OFFSET
private static final int CANADA_OFFSETCountry table offset for Canadian province records.- See Also:
WORLD_OFFSET
private static final int WORLD_OFFSETCountry table offset for world region records.- See Also:
FIPS_RANGE
private static final int FIPS_RANGESize of the FIPS country code range.- See Also:
COUNTRY_BEGIN
private static final int COUNTRY_BEGINDatabase offset where country records begin.- See Also:
STATE_BEGIN_REV0
private static final int STATE_BEGIN_REV0State record start in revision 0 databases.- See Also:
STATE_BEGIN_REV1
private static final int STATE_BEGIN_REV1State record start in revision 1 databases.- See Also:
STRUCTURE_INFO_MAX_SIZE
private static final int STRUCTURE_INFO_MAX_SIZELongest structure info field read.- See Also:
DATABASE_INFO_MAX_SIZE
private static final int DATABASE_INFO_MAX_SIZELongest database info field read.- See Also:
GEOIP_STANDARD
public static final int GEOIP_STANDARDNo cache: every node visit is a disk read.- See Also:
GEOIP_MEMORY_CACHE
public static final int GEOIP_MEMORY_CACHECache flag: load the whole database into RAM and read records from it.- See Also:
GEOIP_CHECK_CACHE
public static final int GEOIP_CHECK_CACHECache flag: stat the database file on each lookup and reload it if it changed.- See Also:
GEOIP_INDEX_CACHE
public static final int GEOIP_INDEX_CACHECache flag: hold the search index in RAM while still reading records from disk.- See Also:
GEOIP_UNKNOWN_SPEED
public static final int GEOIP_UNKNOWN_SPEEDNetSpeed edition: the ISP's connection speed is not classified.- See Also:
GEOIP_DIALUP_SPEED
public static final int GEOIP_DIALUP_SPEEDNetSpeed edition: the connection is dialup or slower.- See Also:
GEOIP_CABLEDSL_SPEED
public static final int GEOIP_CABLEDSL_SPEEDNetSpeed edition: the connection is cable or DSL.- See Also:
GEOIP_CORPORATE_SPEED
public static final int GEOIP_CORPORATE_SPEEDNetSpeed edition: the connection is corporate or faster.- See Also:
SEGMENT_RECORD_LENGTH
private static final int SEGMENT_RECORD_LENGTHRecord length for segment regions, in bytes.- See Also:
STANDARD_RECORD_LENGTH
private static final int STANDARD_RECORD_LENGTHRecord length for standard databases, in bytes.- See Also:
ORG_RECORD_LENGTH
private static final int ORG_RECORD_LENGTHRecord length for org databases, in bytes.- See Also:
MAX_RECORD_LENGTH
private static final int MAX_RECORD_LENGTHLongest record length supported.- See Also:
MAX_ORG_RECORD_LENGTH
private static final int MAX_ORG_RECORD_LENGTHLongest org record read.- See Also:
FULL_RECORD_LENGTH
private static final int FULL_RECORD_LENGTHScratch buffer size for a full record.- See Also:
UNKNOWN_COUNTRY
Country returned when nothing matches.countryCode
Country codes indexed by the database.countryName
Country names indexed by the database.
Constructor Details
LookupService
Create a new lookup service using the specified database file.- Parameters:
databaseFile- String representation of the database file.- Throws:
IOException- if an error occured creating the lookup service from the database file.
LookupService
Create a new lookup service using the specified database file.- Parameters:
databaseFile- the database file.- Throws:
IOException- if an error occured creating the lookup service from the database file.
LookupService
Create a new lookup service using the specified database file.- Parameters:
databaseFile- String representation of the database file.options- database flags to use when opening the database GEOIP_STANDARD read database from disk GEOIP_MEMORY_CACHE cache the database in RAM and read it from RAM- Throws:
IOException- if an error occured creating the lookup service from the database file.
LookupService
Create a new lookup service using the specified database file.- Parameters:
databaseFile- the database file.options- database flags to use when opening the database GEOIP_STANDARD read database from disk GEOIP_MEMORY_CACHE cache the database in RAM and read it from RAM- Throws:
IOException- if an error occured creating the lookup service from the database file.
Method Details
init
Reads meta-data from the database file.- Throws:
IOException- if an error occurs reading from the database file.
close
public void close()Closes the lookup service.getAllCountryNames
getAllCountryCodes
getCountryV6
getCountry
getCountry
Returns the country the IP address is in.- Parameters:
ipAddress- the IP address.- Returns:
- the country the IP address is from.
getCountryV6
Returns the country the IP address is in.- Parameters:
addr- the IP address as Inet6Address.- Returns:
- the country the IP address is from.
getCountry
Returns the country the IP address is in.- Parameters:
ipAddress- the IP address in long format.- Returns:
- the country the IP address is from.
countryToIP
I2P - Write all IPv4 address ranges for the given country to out.- Parameters:
country- ISO two-letter code, matched case-insensitivelyout- caller must close- Throws:
IOException- if a range line cannot be written to out
getID
Looks up the database record ID covering the given IP address.- Parameters:
ipAddress- the address to look up, as a name or a numeric literal- Returns:
- the database ID for the given IP
getID
Looks up the database record ID covering the given IP address.- Parameters:
ipAddress- the address to look up- Returns:
- the database ID for the given IP
getID
public int getID(long ipAddress) Looks up the database record ID covering the given IP address.- Parameters:
ipAddress- the IPv4 address in long format, most significant byte first- Returns:
- the database ID for the given IP
last_netmask
public int last_netmask()Returns the prefix length that the last search stopped at.- Returns:
- the netmask from the last lookup
netmask
public void netmask(int nm) Sets the prefix length thatlast_netmask()reports.- Parameters:
nm- the prefix length in bits, 0-32 for IPv4 or 0-128 for IPv6
getDatabaseInfo
Returns information about the database.- Returns:
- the database edition and build epoch, or an empty DatabaseInfo if the file carries no trailing info block
_check_mtime
void _check_mtime()VoidgetLocationV6
getLocation
Looks up the city record for an IPv4 address. Requires the GeoIP City database.- Parameters:
addr- the address to look up- Returns:
- the location, or null if the database holds no city record for it
getLocation
getRegion
getRegion
Looks up the region record for an IPv4 address.- Parameters:
addr- the address to look up- Returns:
- the country code, country name and two-letter region code
getRegion
Looks up the region record for an IPv4 address.- Parameters:
ipnum- the address in long format, most significant byte first- Returns:
- the region, blank if the database is not a region edition
getLocationV6
Looks up the city record for an IPv6 address.- Parameters:
addr- the address to look up- Returns:
- the location, or null if the database holds no city record for it
getLocation
Looks up the city record for an IPv4 address.- Parameters:
ipnum- the address in long format, most significant byte first- Returns:
- the location, or null if the database holds no city record for it
readCityRecord
Reads the city record for a country seek position.- Parameters:
seekCountry- the country record offset- Returns:
- the location, or null if absent
- Throws:
IOException- if the database read fails
readRecordBuf
Reads a record's bytes into a buffer.- Parameters:
seek- the offset to read frommaxLength- the most bytes to read- Returns:
- the record bytes
- Throws:
IOException- if the database read fails
readString
Reads a NUL-terminated string from the buffer.- Parameters:
buffer- the record buffer- Returns:
- the decoded text
- Throws:
CharacterCodingException- if the bytes are not decodable
readAngle
Reads a latitude or longitude value from the buffer.- Parameters:
buffer- the record buffer- Returns:
- the angle in degrees
readMetroAreaCombo
Reads the combined metro area code from the buffer.- Parameters:
buffer- the record buffer- Returns:
- the metro area code
getOrg
Looks up the owning organisation for an IPv4 address.- Parameters:
addr- the address to look up- Returns:
- the organisation name, or null if the database holds no record for it
getOrg
getOrg
Looks up the owning organisation for an IPv4 address.- Parameters:
ipnum- the address in long format, most significant byte first- Returns:
- the organisation name, or null if the database holds no record for it
getOrgV6
getOrgV6
Looks up the owning organisation for an IPv6 address.- Parameters:
addr- the address to look up- Returns:
- the organisation name, or null if the database holds no record for it
readOrgRecord
Reads the organization name for a seek position.- Parameters:
seekOrg- the record offset- Returns:
- the organization name
- Throws:
IOException- if the database read fails
seekCountryV6
Finds the country index value given an IPv6 address.- Parameters:
addr- the ip address to find in long format.- Returns:
- the country index.
seekCountry
private int seekCountry(long ipAddress) Finds the country index value given an IP address.- Parameters:
ipAddress- the ip address to find in long format.- Returns:
- the country index.
readNode
private void readNode(byte[] buf, int[] x, int offset) Reads one node's two child offsets into x.- Parameters:
buf- the buffer holding the nodex- where the child offsets are storedoffset- the node offset in the database
bytesToLong
private static long bytesToLong(byte[] address) Returns the long version of an IP address given an InetAddress object.- Parameters:
address- the InetAddress.- Returns:
- the long form of the IP address.
unsignedByteToInt
private static int unsignedByteToInt(byte b) Converts a byte to its unsigned value.- Parameters:
b- the byte- Returns:
- the value from 0 to 255