Getting the machine serial number and CPU ID using C/C++ in Linux

后端 未结 5 631
[愿得一人]
[愿得一人] 2020-11-30 01:01

How can I get the machine serial number and CPU ID in a Linux system?

Sample code is highly appreciated.

5条回答
  •  抹茶落季
    2020-11-30 01:22

    #include 
    
    void getPSN(char *PSN)
    {
        int varEAX, varEBX, varECX, varEDX;
        char str[9];
        //%eax=1 gives most significant 32 bits in eax 
        __asm__ __volatile__ ("cpuid"   : "=a" (varEAX), "=b" (varEBX), "=c" (varECX), "=d" (varEDX) : "a" (1));
        sprintf(str, "%08X", varEAX); //i.e. XXXX-XXXX-xxxx-xxxx-xxxx-xxxx
        sprintf(PSN, "%C%C%C%C-%C%C%C%C", str[0], str[1], str[2], str[3], str[4], str[5], str[6], str[7]);
        //%eax=3 gives least significant 64 bits in edx and ecx [if PN is enabled]
        __asm__ __volatile__ ("cpuid"   : "=a" (varEAX), "=b" (varEBX), "=c" (varECX), "=d" (varEDX) : "a" (3));
        sprintf(str, "%08X", varEDX); //i.e. xxxx-xxxx-XXXX-XXXX-xxxx-xxxx
        sprintf(PSN, "%s-%C%C%C%C-%C%C%C%C", PSN, str[0], str[1], str[2], str[3], str[4], str[5], str[6], str[7]);
        sprintf(str, "%08X", varECX); //i.e. xxxx-xxxx-xxxx-xxxx-XXXX-XXXX
        sprintf(PSN, "%s-%C%C%C%C-%C%C%C%C", PSN, str[0], str[1], str[2], str[3], str[4], str[5], str[6], str[7]);
    }
    
    int main()
    {
         char PSN[30]; //24 Hex digits, 5 '-' separators, and a '\0'
         getPSN(PSN);
        printf("%s\n", PSN); //compare with: lshw | grep serial:
         return 0;
    }
    

提交回复
热议问题