代碼主要是造輪子的粮坞,沒有什么需要講解的,主要方便以后查詢初狰。
- 引入需要的頭文件
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <net/if.h>
- 檢測(cè)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;
}
- 獲取當(dāng)前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莫杈。