Linux
下
获
取
CPUID
、硬
盘
序列号与
MAC
地址
在很多系
统软
件的
开发
中,需要使用一些系
统
的唯一性
信息。所以,得到主机的
CPUID
、硬
盘
序列号及网卡
的
MAC
地址,就成个一件很重要的
应
用。
本人
经过
一番
即自己的
钻
研,基本上
实现
了
这
几个功能。需要的准
备
知
识
有:
1.
GCC
的嵌入
汇编
,具体的
GCC
嵌入
汇编
知
识
,
请
参考相
关
手册
2.
ioctl
系
统调
用,具体的
调
用方法,
请查
看手册
页
获
取
CPUID
按照网上提供的
说
明,
CPUID
并不是所有的
Intel CPU
都支持的。如果支持,
汇编调
用
为
:
eax
置
0000_0003
,
调
用
cpuid
。
以下
为实现
代
码
(在我的
CPU
上,并没有得到):
#define cpuid(in,a,b,c,d) asm("cpuid": "=a" (a), "=b" (b), "=c" (c), "=d" (d) : "a" (in));
static int
getcpuid (char *id, size_t max)
{
int i;
unsigned long li, maxi, maxei, ebx, ecx, edx, unused;
cpuid (0, maxi, unused, unused, unused);
maxi &= 0xffff;
if (maxi
{
return -1;
}
cpuid (3, eax, ebx, ecx, edx);
snprintf (id, max, "%08lx %08lx %08lx %08lx", eax, ebx, ecx, edx);
fprintf (stdout, "get cpu id: %s\n", id);
return 0;
}
获
取硬
盘
序列号
这
个的
实现
,采用的是
读
取
/etc/mtab
文件,找到
/
(即根目
录
)挂
载
的
设备
文件,然后打
开
它,再用系
统调
用
ioctl
来
实现
的。
ioctl
第二个参数
为
HDIO_GET_IDENTITY,
获
得指定文件描述符的
标
志号
ioctl
的第三个参数
为
struct hd_driveid *
,在
linux/hdreg.h
中,
struct hd_driveid
的声明有
struct hd_driveid {
unsigned short config; /* lots of obsolete bit flags */
unsigned short cyls; /* Obsolete, "physical" cyls */
unsigned short reserved2; /* reserved (word 2) */
unsigned short heads; /* Obsolete, "physical" heads */
unsigned short track_bytes; /* unformatted bytes per track */
unsigned short sector_bytes; /* unformatted bytes per sector */
unsigned short sectors; /* Obsolete, "physical" sectors per track */
unsigned short vendor0; /* vendor unique */
unsigned short vendor1; /* vendor unique */