我想获取机器的序列号密钥。有什么机构可以帮助我获取机器的序列号吗?

最佳答案

没有为此的Cocoa API。您必须调用Carbon。

#import <Carbon/Carbon.h>
#import<IOKit/IOKitLib.h>
#import <mach/mach.h>

NSString*   UKSystemSerialNumber()
{
    mach_port_t             masterPort;
    kern_return_t           kr = noErr;
    io_registry_entry_t     entry;
    CFTypeRef               prop;
    CFTypeID                propID;
    NSString*               str = nil;

    kr = IOMasterPort(MACH_PORT_NULL, &masterPort);
    if( kr != noErr )
        goto cleanup;
    entry = IORegistryGetRootEntry( masterPort );
    if( entry == MACH_PORT_NULL )
        goto cleanup;
    prop = IORegistryEntrySearchCFProperty(entry, kIODeviceTreePlane, CFSTR("serial-number"), nil, kIORegistryIterateRecursively);
    if( prop == nil )
        goto cleanup;
    propID = CFGetTypeID( prop );
    if( propID != CFDataGetTypeID() )
        goto cleanup;

    const char* buf = [(NSData*)prop bytes];
    int         len = [(NSData*)prop length],
                 x;

    char    secondPart[256];
    char    firstPart[256];
    char*   currStr = secondPart; // Version number starts with second part, then NULLs, then first part.
    int     y = 0;

    for( x = 0; x < len; x++ )
    {
        if( buf[x] > 0 && (y < 255) )
            currStr[y++] = buf[x];
        else if( currStr == secondPart )
        {
            currStr[y] = 0;     // Terminate string.
            currStr = firstPart;
            y = 0;
        }
    }
    currStr[y] = 0; // Terminate string.

    str = [NSString stringWithFormat: @"%s%s", firstPart, secondPart];

cleanup:
    mach_port_deallocate( mach_task_self(), masterPort );

    return str;
}


上面的代码来自here

09-28 03:29