如何从硬盘获取序列号?

使用Win32 API获取PC中所有硬盘的序列号有没有简单的方法?


GetVolumeInformation是你的朋友。


GetVolumeInformation将仅为您提供有关分区卷的信息 ,而不是整个HDD。

您应该使用DeviceIoControl函数获取信息。

这里可能的代码:

#include <atlstr.h>
#include <Windows.h>
#include <winioctl.h>

BOOL getSerial(CString diskSerial) {
  BOOL   bResult = FALSE;

  STORAGE_PROPERTY_QUERY    storagePropertyQuery;
  STORAGE_DESCRIPTOR_HEADER storageDescHeader = { 0 };
  STORAGE_DEVICE_DESCRIPTOR *pDeviceDesc;

  DWORD dwBytes = 0;
  DWORD dwOutBufferSize = 0;
  DWORD dwSerialNumberOffset = 0;

  BYTE *pOutBuffer = nullptr;

  ZeroMemory(&storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY));
  storagePropertyQuery.PropertyId = StorageDeviceProperty;
  storagePropertyQuery.QueryType = PropertyStandardQuery;

  HANDLE hDevice = CreateFile("\.PhysicalDrive0", 0,
                   FILE_SHARE_READ | FILE_SHARE_WRITE,
                   NULL, OPEN_EXISTING, 0, NULL);

  if (hDevice == INVALID_HANDLE_VALUE) {
    std::cout << "Can't get access to HDD.nTerminating." << std::endl;
    exit(EXIT_FAILURE);
  }

  bResult = DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY,
                        &storagePropertyQuery, sizeof(storagePropertyQuery),
                        &storageDescHeader, sizeof(storageDescHeader),
                        &dwBytes, NULL);

  dwOutBufferSize = storageDescHeader.Size;

  try {
    pOutBuffer = new BYTE[dwOutBufferSize];
    ZeroMemory(pOutBuffer, sizeof(pOutBuffer));
  } catch (std::bad_alloc exp) {
    CloseHandle(hDevice);
    std::cout << exp.what() << std::endl;
    return FALSE;
  }

  bResult = DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY,
                        &storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY),
                        pOutBuffer, dwOutBufferSize, &dwBytes, NULL);

  pDeviceDesc = (STORAGE_DEVICE_DESCRIPTOR *)pOutBuffer;
  dwSerialNumberOffset = pDeviceDesc->SerialNumberOffset;
  diskSerial = CString(pOutBuffer + dwSerialNumberOffset);

  std::cout << "Serial Number: " << diskSerial << std::endl;

  delete[] pOutBuffer;
  CloseHandle(hDevice);

  return TRUE;
}

如果安装了多个硬盘驱动器,则应将"\.PhysicalDrive0"更改为"\.PhysicalDrive1"等。

链接地址: http://www.djcxy.com/p/42137.html

上一篇: How to get serial number from hard disks?

下一篇: safe in IIS?