Search code examples
javagoogle-app-engineinetaddress

Avoid using InetAddress - Getting a raw IP address in network byte order


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

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