I need to get the serial numbers of various storage devices. At the moment, the code is written correctly working with the HDD, but when working with SSD, the function returns the wrong result ( 0000_0000_0100_0000_E4D2_5C42_46E3_4D01 ), which I expect.

Also tried using WMI, the result is the same.

The question is: do I use this code correctly when applied to SSD. Is there any other solutions? Feel free to write.

 // HANDLE h = CreateFile(L"\\\\.\\PhysicalDrive0", FILE_ANY_ACCESS , FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); // bool success = h != INVALID_HANDLE_VALUE; std::string getSerialNumber(HANDLE h) { std::string result; static STORAGE_PROPERTY_QUERY spq = { StorageDeviceProperty, PropertyStandardQuery }; union { PVOID buf; PSTR psz; PSTORAGE_DEVICE_DESCRIPTOR psdd; }; ULONG size = sizeof(STORAGE_DEVICE_DESCRIPTOR) + 0x100; ULONG dwError; do { dwError = ERROR_NO_SYSTEM_RESOURCES; if (buf = LocalAlloc(0, size)) { DWORD returned; if (DeviceIoControl(h, IOCTL_STORAGE_QUERY_PROPERTY, &spq, sizeof(spq), buf, size, &returned, 0)) { if (psdd->Version >= sizeof(STORAGE_DEVICE_DESCRIPTOR)) { if (psdd->Size > size) { size = psdd->Size; dwError = ERROR_MORE_DATA; } else { if (psdd->SerialNumberOffset) { result = psz + psdd->SerialNumberOffset; dwError = NOERROR; } else { throw std::runtime_error(std::to_string(ERROR_NO_DATA)); } } } else { throw std::runtime_error(std::to_string(ERROR_GEN_FAILURE)); } } else { throw std::runtime_error(std::to_string(GetLastError())); } LocalFree(buf); } } while (dwError == ERROR_MORE_DATA); return result; } 

I tried to get this serial number from Linux and UEFI - the result is the same, the number is displayed correctly.

I also tried to obtain this GUI serial number using Windows tools — I could not find a solution (but I need to get the number programmatically).

  • your code worked correctly on my hard drives. Getting SN wmic diskdrive get model,name,serialnumber WD10JPVX-22JC3T0 \\. \ PHYSICALDRIVE1 WD-WXP1A560K457 serial wmic diskdrive get model,name,serialnumber WDC WD10JPVX-22JC3T0. Your code issues "WD-WXP1A560K457". Superfluous gaps, but I think it is not critical. - goldstar_labs
  • can you add to the question the output "wmic diskdrive get model, name, serialnumber" (execute on the command line) and output your code on the problem device? - goldstar_labs
  • @goldstar_labs, extra spaces are a solvable problem. works out on HDD correctly, SSD number is incorrectly displayed - Alexander Schetnev
  • @goldstar_labs, tried WMI - the result is the same - Alexander Schetnev
  • one
    Can it be a matter of ssd or interpreting a set of bytes? I had a similar situation with the bill acceptor, when the manufacturer in its software recruited a set of bytes that the device returned incorrectly and displayed an incorrect SN, although the bytes were the same - goldstar_labs

0