Get IP address of WIFI or Hotspot in Android



The following function will get your job done

public String getWifiApIpAddress() {
    try {
         for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
          NetworkInterface intf = en.nextElement();
                if((intf.getDisplayName().toLowerCase().contains("wlan")||intf.getDisplayName().toLowerCase().contains("ap"))) {
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()&& (inetAddress.getAddress().length == 4)) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        }
    } catch (SocketException ex) { }
    return null;
}

NetworkInterface class represents a Network Interface made up of a name, and a list of IP addresses assigned to this interface.
"wlan" Represents WIFI LAN, "ap" Represents Access point.
An access point is a device that creates a wireless local area network, or WLAN.
Access point mode is also called as Hotspot or Portable Hotspot mode.
In this code we check if the IP is not a loopback IP, since the loopback interface has no hardware associated with it, and it is not physically connected to a network.


Comments

Popular posts from this blog

Add/Set collection in Firestore with the Firebase Admin SDK : Python 🐍

Writing to external SD card in Android 5.0 and above

Add/Set array in Firestore with the Firebase Admin SDK : Python 🐍