Question

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()));
}
Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top