iOS 检测Wifi是否打开、IP地址、Wifi名称
2017-06-12 本文已影响0人
Hardy_Hu
代码主要是造轮子的,没有什么需要讲解的,主要方便以后查询。
- 引入需要的头文件
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <net/if.h>
- 检测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;
}
- 获取当前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;
}
- 获取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。