1、在Linux系统中通过C语言获取硬盘序列号,可以借助于ioctl()函数,该函数原型如下:
int ioctl(int fd, unsigned long request, ...);
ioctl的第一个参数是文件标识符,用open()函数打开设备时获取。
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 */
unsigned short vendor2; /* Retired vendor unique */
unsigned char serial_no[20]; /* 0 = not_specified */
unsigned short buf_type; /* Retired */
unsigned short buf_size; /* Retired, 512 byte increments
* 0 = not_specified
*/
……
};
2、源代码如下
#include
//ioctl()的声明头文件
#include
//硬盘参数头文件, hd_driveid结构声明头文件
#include
//文件控制头文件
#include
int main()
{
//用于保存系统返回的硬盘数据信息
struct hd_driveid id;
//这里以第一块硬盘为例,用户可自行修改
//用open函数打开获取文件标识符,类似于windows下的句柄
int fd = open("/dev/sda", O_RDONLY|O_NONBLOCK);
//失败返回
if (fd < 0) {
perror("/dev/sda");
return 1; }
//调用ioctl()
if(!ioctl(fd, HDIO_GET_IDENTITY, &id))
{
printf("Serial Number=%s\n",id.serial_no);
}
return 0;
}
编译完成后,执行效果如下: