Search code examples
javaandroidinetaddress

Occasional error Using InetAddress.getByName()


In my application, I use InetAddress.getByName() quite a bit to convert strings like "192.168.1.56" to InetAddress objects -- mainly because it seems to me to be a good idea to store IP addresses as IP addresses rather than as strings. Up til now, I would have sworn it was pretty foolproof too, but today I discovered a bug. This does not work:

InetAddress ia = InetAddress.getByName ("192.168.1.056");

It would appear that my Android thinks THAT string is a host name, and so it's trying to look it up (which isn't possible, because it's not on a "real" network). Is this something I can work around -- meaning is there a way to insist to getByName that this is an IP address, not a hostname? Or do I need to build method to purge leading zeroes out of IP address strings?? Or is there an Apache utility buried somewhere that might do a better job of this??


Solution

  • It may be that a Regex-wizard could have found a way to fix the IP address string directly, but I don't know how to do that. However, there is something called the Apache SubnetUtils library which is native to Android. SubnetUtils doesn't have a cow over an IP address string with a leading zero in it. My code looks like this:

    public static InetAddress addrFromStr (String addr)
    {
        InetAddress ia = null;
        SubnetUtils su = new SubnetUtils (addr + "/8");
    
        try
        {
            ia = InetAddress.getByName (su.getInfo().getAddress());
        }
        catch (UnknownHostException e)
        { }
    
        return ia;
    }
    

    Basically, I create a SubnetUtils object and then ask it for the IP address -- which is now stripped of any numerical strangeness that InetAddress.getByName() apparently can't handle. (The "/8" business is the CIDR notation subnet mask, and the only thing I can say about it is don't use "/0").