【macOS】MAC地址获取

官网有一个示例,可以在高版本获取网络设备MAC地址官网示例,但是低版本或一部分设备上可能无法解析出。
还有一种办法,是通过命令行获取。执行:

system_profiler

即可获取关于macOS这里的信息:
【macOS】MAC地址获取_第1张图片
查找后,可以通过:

system_profiler SPEthernetDataType

来得到网络设备信息:

@* ~ % system_profiler SPEthernetDataType
Ethernet:

Broadcom 57762-A0:

  Bus: PCI
  Vendor ID: 0x14e4
  Device ID: 0x1682
  Subsystem Vendor ID: 0x14e4
  Subsystem ID: 0x1682
  Revision ID: 0x0000
  PCIe Link Speed: 2.5 GT/s
  PCIe Link Width: x1
  Driver: com.apple.iokit.AppleBCM5701Ethernet
  BSD Device Name: en0
  MAC Address: 00:8a:76:f2:24:0d
  AVB Support: Yes
  Maximum Link Speed: 1 Gb/s

当然,如果要在程序中获取,可以指定返回字符串的格式,命令提供xml、json等返回格式,但低版本(测试时macOS10),不能以json格式返回。所以要做好兼容性,就采用返回xml格式吧,反正高低版本都可以使用。

system_profiler SPEthernetDataType -xml

下面是参考代码:

// 执行命令行
- (NSString *)launchTask:(NSString *)cmd argument:(NSArray *)argv {
    NSString *ret = nil;
    if (cmd) {
        NSTask *task = [[NSTask alloc] init];
        [task setLaunchPath: cmd];
        [task setArguments: argv ? argv : @[]];
        
        NSPipe *outPipe = [[NSPipe alloc] init];
        [task setStandardOutput: outPipe];
        [outPipe release];
        
        [task launch];
        NSData *data = [[outPipe fileHandleForReading] readDataToEndOfFile];
        
        [task waitUntilExit];
        int status =[task terminationStatus];
        [task release]; task = nil;
        
        if(status == 0)
        {
            ret = [[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] autorelease];
        }
    }
    return  ret;
}

// 该函数获取任意一个有效的网络设备MAC地址
- (NSString *)getAnyMacAddress {
    NSString *cmd = @"/usr/sbin/system_profiler";
    NSArray *arguments = @[@"SPEthernetDataType", @"-xml"];
    NSString *plistStr = [self launchTask:cmd argument:arguments];
    
    NSString *finalMacAddress = nil;    // 获取一个有效的MAC地址即可
    NSString *error;
    NSPropertyListFormat format;
    NSArray *ethernetInfoArr = [NSPropertyListSerialization propertyListFromData:[plistStr dataUsingEncoding:NSUTF8StringEncoding] mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
    if (error) {
        NSLog(@"Get MAC address error: %@", error);
    }else {
        for (NSDictionary *oneEthernetInfo in ethernetInfoArr) {
            NSLog(@"%@", oneEthernetInfo);
            NSArray *itemArr = [oneEthernetInfo objectForKey:@"_items"];
            for (NSDictionary *itemDic in itemArr) {
                NSString *macAddress = [itemDic objectForKey:@"spethernet_mac_address"];
                if (macAddress == nil) macAddress = [itemDic objectForKey:@"spethernet_SleepProxyCapable"];
                
                if (macAddress != nil && macAddress.length == 17) {
                    finalMacAddress = macAddress;
                    goto End;
                }
            }
        }
    }
End:
    return finalMacAddress;
}

你可能感兴趣的:(Mac,macos,ios,xcode)