The Mask The Mask - 1 day ago 4
C Question

How do I get the disk drive serial number in C/C++

This has been already answered but it's a C# solution. How do I do this in C or C++?

G-- G--
Answer

There are a few ways to do this. You could make calls using system to get the information.

For Linux:

system("hdparm -i /dev/hda | grep -i serial");

Without using system:

static struct hd_driveid hd;
int fd;

if ((fd = open("/dev/hda", O_RDONLY | O_NONBLOCK)) < 0) {
    printf("ERROR opening /dev/hda\n");
    exit(1);
}

if (!ioctl(fd, HDIO_GET_IDENTITY, &hd)) {
    printf("%.20s\n", hd.serial_no);
} else if (errno == -ENOMSG) {
    printf("No serial number available\n");
} else {
    perror("ERROR: HDIO_GET_IDENTITY");
    exit(1);
}

For Windows:

system("wmic path win32_physicalmedia get SerialNumber");

Without using system (Based on Getting WMI Data ):

hres = pSvc->ExecQuery(
    bstr_t("WQL"),
    bstr_t("SELECT SerialNumber FROM Win32_PhysicalMedia"),
    WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
    NULL,
    &pEnumerator);
hr = pclsObj->Get(L"SerialNumber", 0, &vtProp, 0, 0);
Comments