Question

I can retrieve system serial by this command line:

AnsiString serial = ExecSysCommand("ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}'")
AnsiString ExecSysCommand(AnsiString command)
{
#ifdef __APPLE__
    FILE* pipe = popen(command.c_str(), "r");
    if (!pipe)
        return "ERROR";
    char buffer[128];
    AnsiString result;
    while (!feof(pipe)) {
        if (fgets(buffer, 128, pipe) != NULL)
            result += buffer;
    }
    pclose(pipe);
    return result;
#elif _Windows
    return "";
#endif
}

How can I do it programmatically in C++Builder without using command line?

Was it helpful?

Solution

Use IOKit:

AnsiString GetSerialNumber()
{
    AnsiString result;

    io_service_t platformExpert =
        IOServiceGetMatchingService(kIOMasterPortDefault,
            IOServiceMatching("IOPlatformExpertDevice"));

    if (platformExpert) {
        CFTypeRef serialNumberAsCFString =
            IORegistryEntryCreateCFProperty(platformExpert,
                                            CFSTR(kIOPlatformSerialNumberKey),
                                            kCFAllocatorDefault, 0);
        if (serialNumberAsCFString)
        {
            result = CFStringGetCStringPtr((CFStringRef) serialNumberAsCFString, 0);
            CFRelease(serialNumberAsCFString);
        }

        IOObjectRelease(platformExpert);
    }

    return result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top