如何在安卓中获取wifi热点的IP?

2022-09-03 02:22:56

正如标题所说...我试图在配置为热点时能够获得wifi iface的IP。理想情况下,我想找到适用于所有手机的东西。

当然,在从AP获取信息时,WifiManager是无用的。

幸运的是,我能够通过这样做来获取所有接口的IP:

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    Log.d("IPs", inetAddress.getHostAddress() );
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

这块代码将打印所有接口的所有IP(包括Wifi热点)。主要问题是我找不到识别WiFi接口的方法。这是一个问题,因为有些手机有多个接口(WiMax等)。这是我到目前为止尝试过的:

  • 按wifi iface显示名称过滤:这不是一个好方法,因为显示名称从一个设备更改为另一个设备(wlan0,eth0,wl0.1等)。
  • 按其Mac地址过滤:几乎可以工作,但在某些设备上,热点iface没有MAC地址( iface.getHardwareAddress()返回null)...所以不是一个有效的解决方案。

有什么建议吗?


答案 1

以下是我为获取wifi热点IP所做的工作:

public String getWifiApIpAddress() {
    try {
        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)) {
                        Log.d(TAG, inetAddress.getHostAddress());
                        return inetAddress.getHostAddress();
                    }
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(TAG, ex.toString());
    }
    return null;
}

这将为您提供任何wifi设备的IP地址,这意味着它不仅适用于热点。如果您连接到另一个wifi网络(意味着您未处于热点模式),它将返回一个IP。

您应该首先检查您是否处于AP模式。您可以使用此类:http://www.whitebyte.info/android/android-wifi-hotspot-manager-class


答案 2

您可以使用它。

((WifiManager) mContext.getSystemService(Context.WIFI_SERVICE)).getDhcpInfo().serverAddress

完整代码

private String getHotspotIPAddress() {

    int ipAddress = mContext.getSystemService(Context.WIFI_SERVICE)).getDhcpInfo().serverAddress;

    if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
        ipAddress = Integer.reverseBytes(ipAddress);
    }

    byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();

    String ipAddressString;
    try {
        ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
    } catch (UnknownHostException ex) {
        ipAddressString = "";
    }

    return ipAddressString;

}

推荐