views:

424

answers:

2

Hey,

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()));
}
+1  A: 
// 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);
}
cHao
Excellent! It works perfectly. I dont suppose you could explain what that code does and how I may extend it to work for ipv6?Many thanks
Mylo
Extending it for ipv6 would take a bit of work, as ipv6 addresses can have a run of 0's in them. Add to that, an ipv6 address won't fit in 64 bits (they're 128 bits long). But for the ipv4 address, what it does is get each piece, shift the result 8 bits to the left (since each piece represents one byte, or 8 bits), and adds the piece on.
cHao
+1  A: 

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.

msw