美文网首页
iOS开发之cocoa获取Mac设备硬件信息(序列号、UUID)

iOS开发之cocoa获取Mac设备硬件信息(序列号、UUID)

作者: brilliance_Liu | 来源:发表于2019-05-31 17:22 被阅读0次
    由于最近开发一款Mac软件,需要获取Mac电脑的一些硬件信息,做唯一设备认证。网上资料不多,但最终还是找到了一些,这里做下汇总记录。这里主要写了,获取设备序列号、UUID、硬盘序列号。设备序列号也就是用做苹果官方查询认证的序列号。获取硬盘序列号代码暂时无从考证正确性。但是设备序列号、UUID,亲测都是准确的。获取设备硬件信息,其实iOS/Mac OS下有个IOKit.framework框架。

    ///1.获取设备的UUID,这里记录两种方法

    //方法一
    - (NSString *) get_platform_uuid {
        io_registry_entry_t ioRegistryRoot = IORegistryEntryFromPath(kIOMasterPortDefault, "IOService:/");
        CFStringRef uuidCf = (CFStringRef) IORegistryEntryCreateCFProperty(ioRegistryRoot, CFSTR(kIOPlatformUUIDKey), kCFAllocatorDefault, 0);
        IOObjectRelease(ioRegistryRoot);
        NSString * uuid = (__bridge NSString *)uuidCf;
        CFRelease(uuidCf);
        return uuid;
    }
    
    //方法2,代码执行终端命令获取
    - (NSString *)GetHardwareUUID
    {
        NSTask *task;
        task = [[NSTask alloc] init];
        [task setLaunchPath: @"/usr/sbin/ioreg"];
        
        //ioreg -rd1 -c IOPlatformExpertDevice | grep -E '(UUID)'
        
        
        NSArray *arguments;
        arguments = [NSArray arrayWithObjects: @"-rd1", @"-c",@"IOPlatformExpertDevice",nil];
        [task setArguments: arguments];
        
        NSPipe *pipe;
        pipe = [NSPipe pipe];
        [task setStandardOutput: pipe];
        
        NSFileHandle *file;
        file = [pipe fileHandleForReading];
        
        [task launch];
        
        NSData *data;
        data = [file readDataToEndOfFile];
        
        NSString *string;
        string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
        
        //NSLog (@"grep returned:n%@", string);
        
        NSString *key = @"IOPlatformUUID";
        NSRange range = [string rangeOfString:key];
        
        NSInteger location = range.location + [key length] + 5;
        NSInteger length = 32 + 4;
        range.location = location;
        range.length = length;
        
        NSString *UUID = [string substringWithRange:range];
        
        
        UUID = [UUID stringByReplacingOccurrencesOfString:@"-" withString:@""];
        NSLog(@"UIID:%@",UUID);
        
        return UUID;
    }
    

    ///2.获取mac设备序列号,同样贴出两种获取方式

    方式1
    NSString * GetHardwareSerialNumber()
    {
        NSString * ret = nil;
        io_service_t platformExpert ;
        platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice")) ;
        
        if (platformExpert)    {
            CFTypeRef uuidNumberAsCFString ;
            uuidNumberAsCFString = IORegistryEntryCreateCFProperty(platformExpert, CFSTR("IOPlatformSerialNumber"), kCFAllocatorDefault, 0) ;
            if (uuidNumberAsCFString)    {
                ret = [(__bridge NSString *)(CFStringRef)uuidNumberAsCFString copy];
                CFRelease(uuidNumberAsCFString); uuidNumberAsCFString = NULL;
            }
            IOObjectRelease(platformExpert); platformExpert = 0;
        }
        
        return ret;
    }
    
    ///方式2
    - (NSString *)GetHardwareSerialNumber
    {
        NSTask *task;
        task = [[NSTask alloc] init];
        [task setLaunchPath: @"/usr/sbin/ioreg"];
        
        //ioreg -rd1 -c IOPlatformExpertDevice | grep -E '(UUID)'
        
        
        NSArray *arguments;
        arguments = [NSArray arrayWithObjects: @"-rd1", @"-c",@"IOPlatformExpertDevice",nil];
        [task setArguments: arguments];
        
        NSPipe *pipe;
        pipe = [NSPipe pipe];
        [task setStandardOutput: pipe];
        
        NSFileHandle *file;
        file = [pipe fileHandleForReading];
        
        [task launch];
        
        NSData *data;
        data = [file readDataToEndOfFile];
        
        NSString *string;
        string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
        
        //NSLog (@"grep returned:n%@", string);
        
        NSString *key = @"IOPlatformSerialNumber";
        NSRange range = [string rangeOfString:key];
        
        NSInteger location = range.location + [key length] + 5;
        NSInteger length = 32 + 4;
        range.location = location;
        range.length = length;
        
        NSString *SerialNumber = [string substringWithRange:range];
        
        
        SerialNumber = [SerialNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
    //    NSLog(@"SerialNumber:%@",SerialNumber);
        
        return SerialNumber;
    }
    
    
    

    ///获取mac硬盘信息,包括硬盘序列号。(暂未考证代码准确性)代码出处

    
    void iotest()
    {
        io_iterator_t iterator;
        kern_return_t kr;
        io_object_t   driver;
        
        CFMutableDictionaryRef matchDictionary = IOServiceMatching("AppleAHCIDiskDriver");
        kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchDictionary, &iterator);
        if (kr != kIOReturnSuccess)
        {
            return;
        }
        
        while ((driver = IOIteratorNext(iterator)) != 0)
        {
            CFMutableDictionaryRef properties = NULL;
            kr = IORegistryEntryCreateCFProperties(driver,
                                                   &properties,
                                                   kCFAllocatorDefault,
                                                   kNilOptions);
            
            if (kr != kIOReturnSuccess || properties == NULL)
            {
                continue;
            }
            
            NSLog(@"%@",(__bridge NSDictionary*)properties);//查看所有信息,只要部分的话可以从Dictionary中提取
        }
    }
    ///打印信息
    2019-05-31 16:21:59.894601+0800 MacTestApplication[2746:748659] {
        CFBundleIdentifier = "com.apple.iokit.IOAHCIBlockStorage";
        IOClass = AppleAHCIDiskDriver;
        IOMatchCategory = IODefaultMatchCategory;
        IOMaximumBlockCountRead = 65536;
        IOMaximumBlockCountWrite = 65536;
        IOPlatformPanicAction = 0;
        IOPolledInterface = "AppleAHCIDiskPolledInterface is not serializable";
        IOProbeScore = 0;
        IOProviderClass = IOAHCIDevice;
        "Logical Block Size" = 512;
        Model = "APPLE HDD HTS541010A9E632               ";
        NCQ = 1;
        "Physical Block Size" = 4096;
        "Physical Interconnect Location" = Internal;
        "Queue Depth" = 32;
        "Queue Depth Counters" =     {
            QueueDepths =         (
                1144,
                191,
                27,
                13,
                10,
                9,
                9,
                9,
                7,
                7,
                6,
                5,
                4,
                4,
                4,
                3,
                1,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0
            );
        };
        Revision = JA0AB5N0;
        "SATA Features" = 47;
        "Serial Number" = "      JD8002D8H5L7GD";
        "Time To Ready" = 3812;
        "Trace ID" = 1507360;
    }
    
    
    获取Mac地址
    + (NSString *)getMACAddress:(BOOL)stripColons {
        NSMutableString         *macAddress         = nil;
        NSArray                 *allInterfaces      = (NSArray*)CFBridgingRelease(SCNetworkInterfaceCopyAll());
        NSEnumerator            *interfaceWalker    = [allInterfaces objectEnumerator];
        SCNetworkInterfaceRef   curInterface        = nil;
        
        while ( curInterface = (__bridge SCNetworkInterfaceRef)[interfaceWalker nextObject] ) {
            if ( [(NSString*)SCNetworkInterfaceGetBSDName(curInterface) isEqualToString:@"en0"] ) {
                macAddress = [(NSString*)SCNetworkInterfaceGetHardwareAddressString(curInterface) mutableCopy];
                
                if ( stripColons == YES ) {
                    [macAddress replaceOccurrencesOfString: @":" withString: @"" options: NSLiteralSearch range: NSMakeRange(0, [macAddress length])];
                }
                
                break;
            }
        }
        
        return [macAddress copy];
    }
    

    文章内容搜集于互联网,并作个人笔记之用。(如侵删)
    cocoa获取系统序列号,uuid及Mac地址
    iOS 获取设备信息,mac地址,IP地址,设备名称


    相关文章

      网友评论

          本文标题:iOS开发之cocoa获取Mac设备硬件信息(序列号、UUID)

          本文链接:https://www.haomeiwen.com/subject/tvygtctx.html