Question

I am developing an android app and need to know the device ip.

I have tried with Inet4Address.getLocalHost().getHostAddress() but it gives 127.0.0.1.

So I am establishing a HTTP connection with a server that send the ip back.

But this process creates an issue when there is a gateway between the device and the requested server. In this case I don't get the network's device ip instead I get the gateway ip.

Please help.

Thanks.

No correct solution

OTHER TIPS

First, you may have several network interfaces, one of them is lo. Second, you may have set both ipv4 and ipv6, i.e. have several ip addresses per network interface. Thus, you need to define the ipaddress and net interface you will use and then make a filter. If you just take first address, you will get the same result as after Inet4Address.getLocalHost().getHostAddress()

Assume you want to get ipv4(ipv6) address for first not-loopback interface you find. Then, the following code gives the ip:

static InetAddress ip() throws SocketException {
    Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
    NetworkInterface ni;
    while (nis.hasMoreElements()) {
        ni = nis.nextElement();
        if (!ni.isLoopback()/*not loopback*/ && ni.isUp()/*it works now*/) {
            for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
                //filter for ipv4/ipv6
                if (ia.getAddress().getAddress().length == 4) {
                    //4 for ipv4, 16 for ipv6
                    return ia.getAddress();
                }
            }
        }
    }
    return null;
}

public static void main(String[] args) throws SocketException {
    System.out.println(ip());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top