Mac 网络类型识别

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

  • 获取目前使用的网络接口的名称
  • 遍历所有网络接口,找到使用的那一个
  • 判断网络接口的协议和展示明显,判定是有线(ethernet)还是Wi-Fi
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

 

上一篇:【Java 并发编程】线程锁机制 ( 锁的四种状态 | 无锁状态 | 偏向锁 | 轻量级锁 | 重量级锁 | 锁竞争 | 锁升级 )


下一篇:No log when use commons-loggins and spring-boot