OGeek|极客世界-中国程序员成长平台

标题: ios - 在 iOS 设备上,en0 是否始终是 Wi-Fi? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 09:53
标题: ios - 在 iOS 设备上,en0 是否始终是 Wi-Fi?

我正在尝试使用 getifaddrs() 并搜索 en0 名称来获取 iOS 设备上 wifi 接口(interface)的 IP 地址。这工作正常,但它假定 en0 始终是 Wi-Fi。有什么方法可以确保我查询的接口(interface)是专门的 Wi-Fi 以备将来验证?



Best Answer-推荐答案


我使用以下方法通过查找具有 wifi 站 BSSID 的设备来查找 wifi 信息。它还将有一个 SSID。

以下类方法仅返回 wifi 信息字典。它是一个简单的扩展,还返回设备标签(ifname 变量)。正如您所指出的,它通常是 en0,但如果将来它不是 en0,这将作为确保您拿起 wifi 的一种方式。

+ (NSDictionary *)getWifiInfo {
    NSDictionary *ret=nil;

    // Get the supported interfaces.
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();

    // Find one with a BSSID and return that. This should be the wifi.
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);

        NSLog(@"Network device found = %@", info.description);

        if (info[(__bridge NSString *)kCNNetworkInfoKeyBSSID]) {
            // Return this as it should be the right one given it has a MAC address for the station
            ret=info;
        }
    }

    NSLog(@"Exit: returning wifi info = %@", ret.description);

    return ret;
}

一旦你有了基于 BSSID 的设备标签,你就可以使用 getifaddrs 来获取它的 IP、网关等,知道它是 wifi 设备。

NB这会在 iOS 模拟器中返回 nil,因为没有检测到 wifi,因此为了进行测试,您需要一些解决方法代码来满足您的需求。

一个 hacky 选项是找到与 02:00:00:00:00:00 关联的 MAC 的 IP 地址。 iOS 对编码器隐藏了 MAC 地址,它有这个值。

关于ios - 在 iOS 设备上,en0 是否始终是 Wi-Fi?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32104279/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4