requestRouteToHost IP argument
Asked Answered
M

1

8

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.

Michelle answered 19/2, 2010 at 11:48 Comment(0)
H
9

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;
}
Hessian answered 19/2, 2010 at 12:35 Comment(2)
@Mendenhall From Android Documentation An Internet Protocol (IP) address. This can be either an IPv4 address or an IPv6 address, and in practice you'll have an instance of either Inet4Address or Inet6Address (this class cannot be instantiated directly). Most code does not need to distinguish between the two families, and should use InetAddress.Queridas
So the addrBytes = inetAddress.getAddress(); would not return a 6 byte array?Mendenhall

© 2022 - 2024 — McMap. All rights reserved.