流程
- 1.获取系统中所有具有网络功能的接口配置
- 2.获取当前网络的BSD接口名称
- 3.在接口配置中查找当前网络BSD名称对应的接口本地化名称
- 4.根据本地化名称判断是
以太网 (Ethernet)
还是Wifi
一.获取系统中所有具有网络功能的接口配置
// 获取系统中所有具有网络功能的接口。
- (NSArray <NSDictionary <NSString *,NSString *>*>*)getNetworkServiceorder {
NSMutableArray <NSDictionary <NSString *,NSString *>*>*networkServiceorder = [[NSMutableArray alloc] init];
CFArrayRef ref = SCNetworkInterfaceCopyAll();
NSArray* networkInterfaces = (__bridge NSArray *)(ref);
for(int i = 0; i < networkInterfaces.count; i += 1) {
SCNetworkInterfaceRef interface = (__bridge SCNetworkInterfaceRef)(networkInterfaces[i]);
// 获取本地化名称 例如: ("Ethernet", "FireWire")
CFStringRef displayName = SCNetworkInterfaceGetLocalizedDisplayName(interface);
// 网络接口类型
CFStringRef interfaceName = SCNetworkInterfaceGetInterfaceType(interface);
// 获取bsd接口名称
CFStringRef bsdName = SCNetworkInterfaceGetBSDName(interface);
NSString *nameStr = [NSString stringWithString:(__bridge NSString *)displayName];
NSString *ninterfaceStr = [NSString stringWithString:(__bridge NSString *)interfaceName];
NSString *bsdStr = [NSString stringWithString:(__bridge NSString *)bsdName];
[networkServiceorder addObject:@{
@"name":nameStr,
@"ninterface":ninterfaceStr,
@"bsd":bsdStr
}];
}
return networkServiceorder.copy;
}
二.获取当前网络的BSD接口名称
// 获取当前Bsd接口名称
- (NSString*)getCurrentBsdName {
// 创建系统配置服务器互动会话
SCDynamicStoreRef ds = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("myApplication"), NULL, NULL);
// 获取ip6配置信息
CFDictionaryRef dr6 = SCDynamicStoreCopyValue(ds, CFSTR("State:/Network/Global/IPv6"));
// 获取ip4配置信息
CFDictionaryRef dr4 = SCDynamicStoreCopyValue(ds, CFSTR("State:/Network/Global/IPv4"));
if (dr6) { // ip6
// 获取配置信息Bsd接口名称
CFStringRef router = CFDictionaryGetValue(dr6, CFSTR("PrimaryInterface"));
NSString *routerString = [NSString stringWithString:(__bridge NSString *)router];
CFRelease(dr6);
CFRelease(ds);
return routerString;
} else if(dr4) { // ip4
// 获取配置信息Bsd接口名称
CFStringRef router = CFDictionaryGetValue(dr4, CFSTR("PrimaryInterface"));
NSString *routerString = [NSString stringWithString:(__bridge NSString *)router];
CFRelease(dr4);
CFRelease(ds);
return routerString;
}
CFRelease(ds);
return 0;
}
三.在接口配置中查找当前网络BSD名称对应的接口本地化名称
NSString *currentBsdName = [self getCurrentBsdName];
NSArray *networkServiceorder = [self getNetworkServiceorder];
NSString *localizedDisplayName;
for (NSDictionary <NSString *,NSString *>*dict in networkServiceorder) {
if ([dict[@"bsd"] isEqualToString:currentBsdName]) {
// 获取bsd接口对应的本地化名称
localizedDisplayName = dict[@"name"];
}
}
四.根据本地化名称判断是以太网 (Ethernet)
还是Wifi
if ([localizedDisplayName containsString:@"Ethernet"]) {
NSLog(@"以太网");
}else if ([localizedDisplayName containsString:@"Wi-Fi"]) {
NSLog(@"Wifi");
}else{
NSLog(@"%@", localizedDisplayName);
}