简体   繁体   中英

C/C++ How to get Processor Serial Number on linux

I was wondering how to reliably obtain the Processor Serial Number (PSN) on GNU Linux.

For now I'm using this

#include <stdio.h>
#include <cpuid.h>

unsigned int level = 1;
unsigned eax = 3 /* processor serial number */, ebx = 0, ecx = 0, edx = 0;
__get_cpuid(level, &eax, &ebx, &ecx, &edx);

// byte swap
int first = ((eax >> 24) & 0xff) | ((eax << 8) & 0xff0000) | ((eax >> 8) & 0xff00) | ((eax << 24) & 0xff000000);
int last = ((edx >> 24) & 0xff) | ((edx << 8) & 0xff0000) | ((edx >> 8) & 0xff00) | ((edx << 24) & 0xff000000);

printf("PSN: %08X%08X", first, last);

It gives me PSN: A7060200FFFBEBBF ,
which matches with

sudo dmidecode | grep -P '^\s+ID: ([0-9A-F]{2} ){7}[0-9A-F]{2}$'

output: ID: A7 06 02 00 FF FB EB BF

I only tested on Intel Core i processors, so perhaps it's only working for this type of CPU.

I know that the "Serial Number" is the same across identical CPU model, and is thus not unique.

Also, I'm looking forward for a way of achieving that, that does not rely on executing a shell command and parsing the output.

you can use popen and then parse the result

unsigned char *pk = new unsigned char[100];
    FILE *source = popen("lscpu", "r");
    while (!feof(source)) {
        fread(pk, 100, 1, source);
        for(int i=0;i<100;++i)
        {
            printf("%c",pk[i]);
        }
        printf("\n");
    }
    pclose(source);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM