how to get the IP of the wifi hotspot in Android?

后端 未结 7 1251
半阙折子戏
半阙折子戏 2021-02-02 14:11

As the title says... I\'m trying to be able to get the IP of the wifi iface when it is configured as hotspot. Ideally, I would like to find something that works for all the phon

7条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 15:03

    Here's what I did to get the wifi hotspot ip:

    public String getWifiApIpAddress() {
        try {
            for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en
                    .hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                if (intf.getName().contains("wlan")) {
                    for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr
                            .hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()
                                && (inetAddress.getAddress().length == 4)) {
                            Log.d(TAG, inetAddress.getHostAddress());
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(TAG, ex.toString());
        }
        return null;
    }
    

    This will give you the IP address of any wifi device, which means it's not just for the hotspot. If you're connected to another wifi network (meaning you're not in hotspot mode), it'll return an IP.

    You should check if you are in AP mode first or not. You can use this class for that: http://www.whitebyte.info/android/android-wifi-hotspot-manager-class

提交回复
热议问题