其他分享
首页 > 其他分享> > Mac 网络类型识别

Mac 网络类型识别

作者:互联网

参考 https://www.jianshu.com/p/6ce77a584a3e ,解决了变量释放的问题,实现版本如下

void GetNetworkTyep(std::string& network_type) {
  NSString *use_interface = @"";
  {
    SCDynamicStoreRef ds = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("myApplication"), NULL, NULL);
    // ipv6
    CFPropertyListRef dr6 = SCDynamicStoreCopyValue(ds, CFSTR("State:/Network/Global/IPv6"));
    // ipv4
    CFPropertyListRef dr4 = SCDynamicStoreCopyValue(ds, CFSTR("State:/Network/Global/IPv4"));
    
    if (dr6) {
      use_interface = [(NSDictionary *)CFBridgingRelease(dr6) valueForKey:@"PrimaryInterface"];
    } else if(dr4) {
      use_interface = [(NSDictionary *)CFBridgingRelease(dr4) valueForKey:@"PrimaryInterface"];
    }
    
    CFRelease(ds);
  }
  
  CFArrayRef ref = SCNetworkInterfaceCopyAll();
  
  for(id item in (__bridge NSArray *)(ref)) {
    SCNetworkInterfaceRef interface_ref = (__bridge SCNetworkInterfaceRef)(item);
    // for example : Wi-Fi || AX88772A
    CFStringRef display_name = SCNetworkInterfaceGetLocalizedDisplayName(interface_ref);
    // for example : Ethernet || IEEE80211 || Bridge
    CFStringRef interface_name = SCNetworkInterfaceGetInterfaceType(interface_ref);
    // for example : en[0-9] bridge[0-9]
    CFStringRef bsd_name = SCNetworkInterfaceGetBSDName(interface_ref);
    NSString *name = [NSString stringWithString:(__bridge NSString *)display_name];
    NSString *interface = [NSString stringWithString:(__bridge NSString *)interface_name];
    NSString *bsd = [NSString stringWithString:(__bridge NSString *)bsd_name];
    if ([bsd isEqualToString:use_interface]) {
      if ([interface containsString:@"Ethernet"]) {
        network_type = "Ethernet";
      } else if ([interface containsString:@"802"] || [name containsString:@"Wi-Fi"]) {
        network_type = "Wi-Fi";
      }
    }
    blog(LOG_INFO, "network type :%s*%s*%s %s", name.UTF8String, interface.UTF8String, bsd.UTF8String, network_type.c_str());
  }
  
  CFRelease(ref);
}

p

 

标签:__,bridge,name,Mac,网络,NSString,interface,识别,ref
来源: https://www.cnblogs.com/qwj-sysu/p/15851034.html