Reputation: 87
I am trying to use the MaxMind GeoLite Country database on the Google App Engine. However, I am having difficulty getting the Java API to work as it relies on the InetAddress class which is not available to use on the App Engine.
However, I am not sure if there is a simple workaround as it appears it only uses the InetAddress class to determine the IP of a given hostname. In my case, the hostname is always an IP anyway.
What I need is a way to convert an IP address represented as a String into a byte array of network byte order (which the addr.getAddress() method of the InetAddress class provides).
This is the code the current API uses, I need to find a way of removing all references to InetAddress whilst ensuring it still works!
Thanks for your time.
/**
* Returns the country the IP address is in.
*
* @param ipAddress String version of an IP address, i.e. "127.0.0.1"
* @return the country the IP address is from.
*/
public Country getCountry(String ipAddress) {
InetAddress addr;
try {
addr = InetAddress.getByName(ipAddress);
} catch (UnknownHostException e) {
return UNKNOWN_COUNTRY;
}
return getCountry(bytesToLong(addr.getAddress()));
}
Upvotes: 1
Views: 6464
Reputation: 43487
All 12000+ entries in the GeoIPCountryWhois database are of the form:
"4.17.135.32","4.17.135.63","68257568","68257599","CA","Canada"
break the dotted quad address you have into substrings and range check them that way.
Upvotes: 1
Reputation: 86504
// note: this is ipv4 specific, and i haven't tried to compile it.
long ipAsLong = 0;
for (String byteString : ipAddress.split("\\."))
{
ipAsLong = (ipAsLong << 8) | Integer.parseInt(byteString);
}
Upvotes: 1