Get your Pentium IV CPU ID (or serial number)
bjarne
C、C++ (2003-05-06 20:06:09)
Sometime, in a encryption program or a software liscencing program, we need to get the unique ID of a machine. P4 CPU ID provides this facility. But there is no way for you to get this ID (or serial number) by calling standard C function or Win32 API function. The only way is to use an Intel instruction called: CPUID. Here is the function I always use in my own program, it compiles and works fine in Visual C++. So, if you feel it is good for you, just copy the function source code and use it.
#include <stdio.h>
struct cpuid_t
{
unsigned long id0;
unsigned long id1;
unsigned long id2;
unsigned long id3;
};
inline cpuid_t getCPUID(unsigned long func_idx)
{
cpuid_t id;
__asm{
mov eax, func_idx
cpuid
mov id.id0, eax
mov id.id1, ebx
mov id.id2, ecx
mov id.id3, edx
}
return id;
}
void main()
{
for(int j=0; j<2; j++)
{
for(int i=0; i<4; i++)
{
unsigned long k=i+(j?0x80000000:0);
cpuid_t id=getCPUID(k);
printf("your CPU id is: [0x%xH]%x-%x-%x-%x\n", k, id.id0, id.id1, id.id2, id.id3);
}
}
}
Here the func_idx is the function index. Different index will give you different id content. For detail, please download and read the Intel IA32 intruction set reference from www.intel.com.
Here, I want to emphasize that I don't recommend heavy use of assembly code directly, but for some of the special jobs you need to do, you probably must use some embedded assembly code in your C/C++ code.
I will talk about this more later. Enjoy!