Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

requestRouteToHost IP argument

Tags:

android

For checking internet access on device I use requestRouteToHost function, but it's second argument has integer type - what i has to put in it? Is it int-view of IP like [1] function makes? I think there is more simple way by using default android functions. Can somebody tell me?

[1] -->

public static Long ipToInt(String addr) {
        String[] addrArray = addr.split("\\.");

        long num = 0;
        for (int i=0;i<addrArray.length;i++) {
            int power = 3-i;

            num += ((Integer.parseInt(addrArray[i])%256 * Math.pow(256,power)));
        }
        return num;
    }

Thanks.

like image 462
Dmytro Avatar asked Feb 19 '10 11:02

Dmytro


1 Answers

While there is a method in Android to convert a String IP address into an int, it is not part of the SDK. Here's the implementation:

public static int lookupHost(String hostname) {
    InetAddress inetAddress;
    try {
        inetAddress = InetAddress.getByName(hostname);
    } catch (UnknownHostException e) {
        return -1;
    }
    byte[] addrBytes;
    int addr;
    addrBytes = inetAddress.getAddress();
    addr = ((addrBytes[3] & 0xff) << 24)
            | ((addrBytes[2] & 0xff) << 16)
            | ((addrBytes[1] & 0xff) << 8)
            |  (addrBytes[0] & 0xff);
    return addr;
}
like image 102
CommonsWare Avatar answered Nov 15 '22 19:11

CommonsWare