Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Find the device's ip address when it's hosting a hotspot

I need to find the device's ip address when it's hosting a hotspot. I've used this code so far :

//if is using Hotspot
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
    NetworkInterface intf = en.nextElement();
    if (intf.getName().contains("wlan")) {
        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
            InetAddress inetAddress = enumIpAddr.nextElement();
            if (!inetAddress.isLoopbackAddress() && (inetAddress.getAddress().length == 4)) {
                return inetAddress.getHostAddress();
            }
        }
    }
}

This works quite fine but the wifi NetworkInterface name differs on some devices. So I have to find the device's wifi NetworkInterface name (for its hotspot) first. How can I find this name? Or is there a better approach to find the device's ip address?

/// Finding the right ip address by the MAC also doesn't seem to work

like image 381
user2224350 Avatar asked Feb 15 '14 23:02

user2224350


1 Answers

At first I tried to fetch the MAC address of the WiFi interface to compare it with the MAC address of each interface. But it turns out, that at least on my N4 running CM the MAC of the WiFi interface changes when turning on the Hotspot.

So I wrote some code to walk though the list of devices to find something to identify the wifi interface. This code works perfectly on my N4:

private String getWifiIp() throws SocketException {
    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            en.hasMoreElements(); ) {
        NetworkInterface intf = en.nextElement();
        if (intf.isLoopback()) {
            continue;
        }
        if (intf.isVirtual()) {
            continue;
        }
        if (!intf.isUp()) {
            continue;
        }
        if (intf.isPointToPoint()) {
            continue;
        }
        if (intf.getHardwareAddress() == null) {
            continue;
        }
        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                enumIpAddr.hasMoreElements(); ) {
            InetAddress inetAddress = enumIpAddr.nextElement();
            if (inetAddress.getAddress().length == 4) {
                return inetAddress.getHostAddress();
            }
        }
    }
    return null;
}

Only one single interface matches all conditions: wlan0.

Possible other solution:

Walk trough some most common interface names and try to find them in the list: new String[] { "wlan0", "eth0", ...];

like image 166
flx Avatar answered Jan 19 '23 12:01

flx