美文网首页IOS开发
iOS 检测Wifi是否打开、IP地址、Wifi名称

iOS 检测Wifi是否打开、IP地址、Wifi名称

作者: Hardy_Hu | 来源:发表于2017-06-12 10:40 被阅读0次

    代码主要是造轮子的,没有什么需要讲解的,主要方便以后查询。

    1. 引入需要的头文件
    #import <ifaddrs.h>
    #import <arpa/inet.h>
    #import <SystemConfiguration/CaptiveNetwork.h>
    #import <net/if.h>
    
    1. 检测WIFI功能是否打开
    +(BOOL) isWiFiOpened
    {
        NSCountedSet * cset = [NSCountedSet new];
        struct ifaddrs *interfaces;
        if( ! getifaddrs(&interfaces) )
        {
            for( struct ifaddrs *interface = interfaces; interface; interface = interface->ifa_next)
            {
                if ( (interface->ifa_flags & IFF_UP) == IFF_UP )
                {
                    [cset addObject:[NSString stringWithUTF8String:interface->ifa_name]];
                }
            }
        }
        return [cset countForObject:@"awdl0"] > 1 ? YES : NO;
    }
    
    1. 获取当前IP地址
    +(nullable NSString*)getCurrentWifiIP
    {
        NSString *address = nil;
        struct ifaddrs *interfaces = NULL;
        struct ifaddrs *temp_addr = NULL;
        int success = 0;
        // retrieve the current interfaces - returns 0 on success
        success = getifaddrs(&interfaces);
        if (success == 0) {
            // Loop through linked list of interfaces
            temp_addr = interfaces;
            while(temp_addr != NULL) {
                if(temp_addr->ifa_addr->sa_family == AF_INET) {
                    // Check if interface is en0 which is the wifi connection on the iPhone
                    if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                        // Get NSString from C String
                        address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    }
                }
                temp_addr = temp_addr->ifa_next;
            }
        }
        // Free memory
        freeifaddrs(interfaces);
        return address;
    }
    
    1. 获取WIFI名称
    +(nullable NSString *)getCurretWiFiSsid
    {
        NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
        NSLog(@"Supported interfaces: %@", ifs);
        id info = nil;
        for (NSString *ifnam in ifs)
        {
            info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
            NSLog(@"%@ => %@", ifnam, info);
            if (info && [info count]) { break; }
        }
        return [(NSDictionary*)info objectForKey:@"SSID"];
    }
    

    惯例代码上传到gitHub

    相关文章

      网友评论

        本文标题:iOS 检测Wifi是否打开、IP地址、Wifi名称

        本文链接:https://www.haomeiwen.com/subject/fnflqxtx.html