获取硬盘序列号,computerID,硬盘名称等 win7

来源:互联网 发布:淘宝五金冠店铺多少钱 编辑:程序博客网 时间:2024/06/05 18:58

修改后的,可以直接拿来在MFC中使用。 

头文件

DiskInfo.h

#define PRINTING_TO_CONSOLE_ALLOWED#include <stdlib.h>#include <stdio.h>#include <stddef.h>#include <string.h>#include <windows.h>#include <winioctl.h>#include <Iphlpapi.h>#include <Assert.h>#pragma comment(lib, "iphlpapi.lib")<span style="white-space:pre"></span>//  special include from the MS DDK//#include "c:\win2kddk\inc\ddk\ntddk.h"//#include "c:\win2kddk\inc\ntddstor.h"#define  TITLE   "DiskId32"//char HardDriveSerialNumber [1024];//char HardDriveModelNumber [1024];//int PRINT_DEBUG = false;static void dump_buffer (const char* title,<span style="white-space:pre"></span>const unsigned char* buffer,<span style="white-space:pre"></span>int len);   //  Required to ensure correct PhysicalDrive IOCTL structure setup#pragma pack(1)#define  IDENTIFY_BUFFER_SIZE  512   //  IOCTL commands#define  DFP_GET_VERSION          0x00074080#define  DFP_SEND_DRIVE_COMMAND   0x0007c084#define  DFP_RECEIVE_DRIVE_DATA   0x0007c088#define  FILE_DEVICE_SCSI              0x0000001b#define  IOCTL_SCSI_MINIPORT_IDENTIFY  ((FILE_DEVICE_SCSI << 16) + 0x0501)#define  IOCTL_SCSI_MINIPORT 0x0004D008  //  see NTDDSCSI.H for definition#define SMART_GET_VERSION               CTL_CODE(IOCTL_DISK_BASE, 0x0020, METHOD_BUFFERED, FILE_READ_ACCESS)#define SMART_SEND_DRIVE_COMMAND        CTL_CODE(IOCTL_DISK_BASE, 0x0021, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)#define SMART_RCV_DRIVE_DATA            CTL_CODE(IOCTL_DISK_BASE, 0x0022, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)typedef struct _GETVERSIONINPARAMS {        UCHAR    bVersion;               // Binary driver version.        UCHAR    bRevision;              // Binary driver revision.        UCHAR    bReserved;              // Not used.        UCHAR    bIDEDeviceMap;          // Bit map of IDE devices.        ULONG   fCapabilities;          // Bit mask of driver capabilities.        ULONG   dwReserved[4];          // For future use.} GETVERSIONINPARAMS, *PGETVERSIONINPARAMS, *LPGETVERSIONINPARAMS;   //  GETVERSIONOUTPARAMS contains the data returned from the    //  Get Driver Version function.typedef struct _GETVERSIONOUTPARAMS{   BYTE bVersion;      // Binary driver version.   BYTE bRevision;     // Binary driver revision.   BYTE bReserved;     // Not used.   BYTE bIDEDeviceMap; // Bit map of IDE devices.   DWORD fCapabilities; // Bit mask of driver capabilities.   DWORD dwReserved[4]; // For future use.} GETVERSIONOUTPARAMS, *PGETVERSIONOUTPARAMS, *LPGETVERSIONOUTPARAMS;   //  Bits returned in the fCapabilities member of GETVERSIONOUTPARAMS #define  CAP_IDE_ID_FUNCTION             1  // ATA ID command supported#define  CAP_IDE_ATAPI_ID                2  // ATAPI ID command supported#define  CAP_IDE_EXECUTE_SMART_FUNCTION  4  // SMART commannds supported   //  IDE registerstypedef struct _IDEREGS{   BYTE bFeaturesReg;       // Used for specifying SMART "commands".   BYTE bSectorCountReg;    // IDE sector count register   BYTE bSectorNumberReg;   // IDE sector number register   BYTE bCylLowReg;         // IDE low order cylinder value   BYTE bCylHighReg;        // IDE high order cylinder value   BYTE bDriveHeadReg;      // IDE drive/head register   BYTE bCommandReg;        // Actual IDE command.   BYTE bReserved;          // reserved for future use.  Must be zero.} IDEREGS, *PIDEREGS, *LPIDEREGS;   //  SENDCMDINPARAMS contains the input parameters for the    //  Send Command to Drive function.typedef struct _SENDCMDINPARAMS{   DWORD     cBufferSize;   //  Buffer size in bytes   IDEREGS   irDriveRegs;   //  Structure with drive register values.   BYTE bDriveNumber;       //  Physical drive number to send                             //  command to (0,1,2,3).   BYTE bReserved[3];       //  Reserved for future expansion.   DWORD     dwReserved[4]; //  For future use.   BYTE      bBuffer[1];    //  Input buffer.} SENDCMDINPARAMS, *PSENDCMDINPARAMS, *LPSENDCMDINPARAMS;   //  Valid values for the bCommandReg member of IDEREGS.#define  IDE_ATAPI_IDENTIFY  0xA1  //  Returns ID sector for ATAPI.#define  IDE_ATA_IDENTIFY    0xEC  //  Returns ID sector for ATA.   // Status returned from drivertypedef struct _DRIVERSTATUS{   BYTE  bDriverError;  //  Error code from driver, or 0 if no error.   BYTE  bIDEStatus;    //  Contents of IDE Error register.                        //  Only valid when bDriverError is SMART_IDE_ERROR.   BYTE  bReserved[2];  //  Reserved for future expansion.   DWORD  dwReserved[2];  //  Reserved for future expansion.} DRIVERSTATUS, *PDRIVERSTATUS, *LPDRIVERSTATUS;   // Structure returned by PhysicalDrive IOCTL for several commandstypedef struct _SENDCMDOUTPARAMS{   DWORD         cBufferSize;   //  Size of bBuffer in bytes   DRIVERSTATUS  DriverStatus;  //  Driver status structure.   BYTE          bBuffer[1];    //  Buffer of arbitrary length in which to store the data read from the                                                       // drive.} SENDCMDOUTPARAMS, *PSENDCMDOUTPARAMS, *LPSENDCMDOUTPARAMS;   // The following struct defines the interesting part of the IDENTIFY   // buffer:typedef struct _IDSECTOR{   USHORT  wGenConfig;   USHORT  wNumCyls;   USHORT  wReserved;   USHORT  wNumHeads;   USHORT  wBytesPerTrack;   USHORT  wBytesPerSector;   USHORT  wSectorsPerTrack;   USHORT  wVendorUnique[3];   CHAR    sSerialNumber[20];   USHORT  wBufferType;   USHORT  wBufferSize;   USHORT  wECCSize;   CHAR    sFirmwareRev[8];   CHAR    sModelNumber[40];   USHORT  wMoreVendorUnique;   USHORT  wDoubleWordIO;   USHORT  wCapabilities;   USHORT  wReserved1;   USHORT  wPIOTiming;   USHORT  wDMATiming;   USHORT  wBS;   USHORT  wNumCurrentCyls;   USHORT  wNumCurrentHeads;   USHORT  wNumCurrentSectorsPerTrack;   ULONG   ulCurrentSectorCapacity;   USHORT  wMultSectorStuff;   ULONG   ulTotalAddressableSectors;   USHORT  wSingleWordDMA;   USHORT  wMultiWordDMA;   BYTE    bReserved[128];} IDSECTOR, *PIDSECTOR;typedef struct _SRB_IO_CONTROL{   ULONG HeaderLength;   UCHAR Signature[8];   ULONG Timeout;   ULONG ControlCode;   ULONG ReturnCode;   ULONG Length;} SRB_IO_CONTROL, *PSRB_IO_CONTROL;   // Define global buffers.//BYTE IdOutCmd [sizeof (SENDCMDOUTPARAMS) + IDENTIFY_BUFFER_SIZE - 1];BOOL DoIDENTIFY (HANDLE, PSENDCMDINPARAMS, PSENDCMDOUTPARAMS, BYTE, BYTE,                 PDWORD);   //  Max number of drives assuming primary/secondary, master/slave topology#define  MAX_IDE_DRIVES  16class CDiskInfo{public:<span style="white-space:pre"></span>CDiskInfo(void);<span style="white-space:pre"></span>~CDiskInfo(void);public:<span style="white-space:pre"></span>char HardDriveSerialNumber [1024];<span style="white-space:pre"></span>char HardDriveModelNumber [1024];<span style="white-space:pre"></span>int  m_nID;<span style="white-space:pre"></span>BYTE IdOutCmd [sizeof (SENDCMDOUTPARAMS) + IDENTIFY_BUFFER_SIZE - 1];<span style="white-space:pre"></span>char m_Macstring [256];public:<span style="white-space:pre"></span>int ReadPhysicalDriveInNTWithAdminRights (void); // 以管理员权限获取硬盘信息<span style="white-space:pre"></span>char *ConvertToString (DWORD diskdata [256],int firstIndex,int lastIndex,char* buf);<span style="white-space:pre"></span>void PrintIdeInfo (int drive, DWORD diskdata [256]); <span style="white-space:pre"></span>BOOL DoIDENTIFY (HANDLE, PSENDCMDINPARAMS, PSENDCMDOUTPARAMS, BYTE, BYTE,PDWORD);<span style="white-space:pre"></span>void WriteConstantString (char *entry, char *string);<span style="white-space:pre"></span>void GetDeviceInfo();<span style="white-space:pre"></span>char* GetHardDriveSerialNumber(); // 序列号<span style="white-space:pre"></span>char* GetHardDriveModelNumber();  // 品牌<span style="white-space:pre"></span>int GetComputerID();<span style="white-space:pre"></span>  //  <span style="white-space:pre"></span>void PrintMACaddress(unsigned char MACData[]) ;//MAC地址<span style="white-space:pre"></span>DWORD GetMACaddress(void);<span style="white-space:pre"></span>char* GetMACAddressstring();};//////////////////////////////////////////////////////////////////////////
 源文件

DiskInfo.cpp

</pre><pre name="code" class="cpp">#include "DiskInfo.h"#include <iostream>#include <string>int PRINT_DEBUG = false;using namespace  std;std::string& trim(std::string &);CDiskInfo::CDiskInfo(void){}CDiskInfo::~CDiskInfo(void){}void CDiskInfo::WriteConstantString (char *entry, char *string){}void CDiskInfo:: PrintMACaddress(unsigned char MACData[]){<span style="white-space: pre;"></span>#ifdef PRINTING_TO_CONSOLE_ALLOWED<span style="white-space: pre;"></span><span style="white-space: pre;"></span>printf("\nMAC Address: %02X-%02X-%02X-%02X-%02X-%02X\n", <span style="white-space: pre;"></span>MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);<span style="white-space: pre;"></span>#endif<span style="white-space: pre;"></span><span style="white-space: pre;"></span>//char string [256];<span style="white-space: pre;"></span>sprintf (m_Macstring, "%02X-%02X-%02X-%02X-%02X-%02X", MACData[0], MACData[1], <span style="white-space: pre;"></span>MACData[2], MACData[3], MACData[4], MACData[5]);<span style="white-space: pre;"></span>//WriteConstantString ("MACaddress", string);}void CDiskInfo::PrintIdeInfo (int drive, DWORD diskdata [256]){<span style="white-space: pre;"></span>char serialNumber [1024];<span style="white-space: pre;"></span>char modelNumber [1024];<span style="white-space: pre;"></span>char revisionNumber [1024];<span style="white-space: pre;"></span>char bufferSize [32];<span style="white-space: pre;"></span><span style="white-space: pre;"></span>__int64 sectors = 0;<span style="white-space: pre;"></span>__int64 bytes = 0;<span style="white-space: pre;"></span><span style="white-space: pre;"></span>//  copy the hard drive serial number to the buffer<span style="white-space: pre;"></span>ConvertToString (diskdata, 10, 19, serialNumber);<span style="white-space: pre;"></span>ConvertToString (diskdata, 27, 46, modelNumber);<span style="white-space: pre;"></span>ConvertToString (diskdata, 23, 26, revisionNumber);<span style="white-space: pre;"></span>sprintf (bufferSize, "%u", diskdata [21] * 512);<span style="white-space: pre;"></span><span style="white-space: pre;"></span>if (0 == HardDriveSerialNumber [0] &&<span style="white-space: pre;"></span>//  serial number must be alphanumeric<span style="white-space: pre;"></span>//  (but there can be leading spaces on IBM drives)<span style="white-space: pre;"></span>(isalnum (serialNumber [0]) || isalnum (serialNumber [19])))<span style="white-space: pre;"></span>{<span style="white-space: pre;"></span>strcpy (HardDriveSerialNumber, serialNumber);<span style="white-space: pre;"></span>strcpy (HardDriveModelNumber, modelNumber);<span style="white-space: pre;"></span>}<span style="white-space: pre;"></span>#ifdef PRINTING_TO_CONSOLE_ALLOWED<span style="white-space: pre;"></span><span style="white-space: pre;"></span>//  calculate size based on 28 bit or 48 bit addressing<span style="white-space: pre;"></span>//  48 bit addressing is reflected by bit 10 of word 83<span style="white-space: pre;"></span>if (diskdata [83] & 0x400) <span style="white-space: pre;"></span>sectors = diskdata [103] * 65536I64 * 65536I64 * 65536I64 + <span style="white-space: pre;"></span>diskdata [102] * 65536I64 * 65536I64 + <span style="white-space: pre;"></span>diskdata [101] * 65536I64 + <span style="white-space: pre;"></span>diskdata [100];<span style="white-space: pre;"></span>else<span style="white-space: pre;"></span>sectors = diskdata [61] * 65536 + diskdata [60];<span style="white-space: pre;"></span>//  there are 512 bytes in a sector<span style="white-space: pre;"></span>bytes = sectors * 512;<span style="white-space: pre;"></span>printf ("Drive Size________________________: %I64d bytes\n",<span style="white-space: pre;"></span>bytes);<span style="white-space: pre;"></span>#endif  // PRINTING_TO_CONSOLE_ALLOWED<span style="white-space: pre;"></span><span style="white-space: pre;"></span>char string1 [1000];<span style="white-space: pre;"></span>sprintf (string1, "Drive%dModelNumber", drive);<span style="white-space: pre;"></span>WriteConstantString (string1, modelNumber);<span style="white-space: pre;"></span><span style="white-space: pre;"></span>sprintf (string1, "Drive%dSerialNumber", drive);<span style="white-space: pre;"></span>WriteConstantString (string1, serialNumber);<span style="white-space: pre;"></span><span style="white-space: pre;"></span>sprintf (string1, "Drive%dControllerRevisionNumber", drive);<span style="white-space: pre;"></span>WriteConstantString (string1, revisionNumber);<span style="white-space: pre;"></span><span style="white-space: pre;"></span>sprintf (string1, "Drive%dControllerBufferSize", drive);<span style="white-space: pre;"></span>WriteConstantString (string1, bufferSize);<span style="white-space: pre;"></span><span style="white-space: pre;"></span>sprintf (string1, "Drive%dType", drive);<span style="white-space: pre;"></span>if (diskdata [0] & 0x0080)<span style="white-space: pre;"></span>WriteConstantString (string1, "Removable");<span style="white-space: pre;"></span>else if (diskdata [0] & 0x0040)<span style="white-space: pre;"></span>WriteConstantString (string1, "Fixed");<span style="white-space: pre;"></span>else<span style="white-space: pre;"></span>WriteConstantString (string1, "Unknown");}int CDiskInfo::ReadPhysicalDriveInNTWithAdminRights (void) // 已管理员权限读取物理硬盘信息{   int done = FALSE;   int drive = 0;   for (drive = 0; drive < MAX_IDE_DRIVES; drive++)   {      HANDLE hPhysicalDriveIOCTL = 0;         //  Try to get a handle to PhysicalDrive IOCTL, report failure         //  and exit if can't.      char driveName [256];      sprintf (driveName, "\\\\.\\PhysicalDrive%d", drive);         //  Windows NT, Windows 2000, must have admin rights      hPhysicalDriveIOCTL = CreateFile (driveName,                               GENERIC_READ | GENERIC_WRITE,                                FILE_SHARE_READ | FILE_SHARE_WRITE , NULL,                               OPEN_EXISTING, 0, NULL);      // if (hPhysicalDriveIOCTL == INVALID_HANDLE_VALUE)      //    printf ("Unable to open physical drive %d, error code: 0x%lX\n",      //            drive, GetLastError ());      if (hPhysicalDriveIOCTL == INVALID_HANDLE_VALUE)      {#ifdef PRINTING_TO_CONSOLE_ALLOWED         if (PRINT_DEBUG) <span style="white-space: pre;"></span> printf ("\n%d ReadPhysicalDriveInNTWithAdminRights ERROR"<span style="white-space: pre;"></span> "\nCreateFile(%s) returned INVALID_HANDLE_VALUE\n",<span style="white-space: pre;"></span> <span style="white-space: pre;"></span> __LINE__, driveName);#endif      }      else      {         GETVERSIONOUTPARAMS VersionParams;         DWORD               cbBytesReturned = 0;            // Get the version, etc of PhysicalDrive IOCTL         memset ((void*) &VersionParams, 0, sizeof(VersionParams));         if ( ! DeviceIoControl (hPhysicalDriveIOCTL, DFP_GET_VERSION,                   NULL,                    0,                   &VersionParams,                   sizeof(VersionParams),                   &cbBytesReturned, NULL) )         {         #ifdef PRINTING_TO_CONSOLE_ALLOWED            if (PRINT_DEBUG)            {<span style="white-space: pre;"></span>           DWORD err = GetLastError ();<span style="white-space: pre;"></span>           printf ("\n%d ReadPhysicalDriveInNTWithAdminRights ERROR"<span style="white-space: pre;"></span>               "\nDeviceIoControl(%d, DFP_GET_VERSION) returned 0, error is %d\n",<span style="white-space: pre;"></span>               __LINE__, (int) hPhysicalDriveIOCTL, (int) err);<span style="white-space: pre;"></span>    }#endif         }            // If there is a IDE device at number "i" issue commands            // to the device         if (VersionParams.bIDEDeviceMap <= 0)         {#ifdef PRINTING_TO_CONSOLE_ALLOWED            if (PRINT_DEBUG)<span style="white-space: pre;"></span>            printf ("\n%d ReadPhysicalDriveInNTWithAdminRights ERROR"<span style="white-space: pre;"></span>                "\nNo device found at position %d (%d)\n",<span style="white-space: pre;"></span>                __LINE__, (int) drive, (int) VersionParams.bIDEDeviceMap);#endif         }         else         {            BYTE             bIDCmd = 0;   // IDE or ATAPI IDENTIFY cmd            SENDCMDINPARAMS  scip;            //SENDCMDOUTPARAMS OutCmd;<span style="white-space: pre;"></span>   // Now, get the ID sector for all IDE devices in the system.               // If the device is ATAPI use the IDE_ATAPI_IDENTIFY command,               // otherwise use the IDE_ATA_IDENTIFY command            bIDCmd = (VersionParams.bIDEDeviceMap >> drive & 0x10) ? \                      IDE_ATAPI_IDENTIFY : IDE_ATA_IDENTIFY;            memset (&scip, 0, sizeof(scip));            memset (IdOutCmd, 0, sizeof(IdOutCmd));            if ( DoIDENTIFY (hPhysicalDriveIOCTL,                        &scip,                        (PSENDCMDOUTPARAMS)&IdOutCmd,                        (BYTE) bIDCmd,                       (BYTE) drive,                       &cbBytesReturned))            {               DWORD diskdata [256];               int ijk = 0;               USHORT *pIdSector = (USHORT *)                             ((PSENDCMDOUTPARAMS) IdOutCmd) -> bBuffer;               for (ijk = 0; ijk < 256; ijk++)                  diskdata [ijk] = pIdSector [ijk];               PrintIdeInfo (drive, diskdata);               done = TRUE;            }<span style="white-space: pre;"></span>    }         CloseHandle (hPhysicalDriveIOCTL);      }   }   return done;}BOOL CDiskInfo::DoIDENTIFY (HANDLE hPhysicalDriveIOCTL, PSENDCMDINPARAMS pSCIP,                 PSENDCMDOUTPARAMS pSCOP, BYTE bIDCmd, BYTE bDriveNum,                 PDWORD lpcbBytesReturned){<span style="white-space: pre;"></span>// Set up data structures for IDENTIFY command.<span style="white-space: pre;"></span>pSCIP -> cBufferSize = IDENTIFY_BUFFER_SIZE;<span style="white-space: pre;"></span>pSCIP -> irDriveRegs.bFeaturesReg = 0;<span style="white-space: pre;"></span>pSCIP -> irDriveRegs.bSectorCountReg = 1;<span style="white-space: pre;"></span>//pSCIP -> irDriveRegs.bSectorNumberReg = 1;<span style="white-space: pre;"></span>pSCIP -> irDriveRegs.bCylLowReg = 0;<span style="white-space: pre;"></span>pSCIP -> irDriveRegs.bCylHighReg = 0;<span style="white-space: pre;"></span><span style="white-space: pre;"></span>// Compute the drive number.<span style="white-space: pre;"></span>pSCIP -> irDriveRegs.bDriveHeadReg = 0xA0 | ((bDriveNum & 1) << 4);<span style="white-space: pre;"></span><span style="white-space: pre;"></span>// The command can either be IDE identify or ATAPI identify.<span style="white-space: pre;"></span>pSCIP -> irDriveRegs.bCommandReg = bIDCmd;<span style="white-space: pre;"></span>pSCIP -> bDriveNumber = bDriveNum;<span style="white-space: pre;"></span>pSCIP -> cBufferSize = IDENTIFY_BUFFER_SIZE;<span style="white-space: pre;"></span><span style="white-space: pre;"></span>return ( DeviceIoControl (hPhysicalDriveIOCTL, DFP_RECEIVE_DRIVE_DATA,<span style="white-space: pre;"></span>(LPVOID) pSCIP,<span style="white-space: pre;"></span>sizeof(SENDCMDINPARAMS) - 1,<span style="white-space: pre;"></span>(LPVOID) pSCOP,<span style="white-space: pre;"></span>sizeof(SENDCMDOUTPARAMS) + IDENTIFY_BUFFER_SIZE - 1,<span style="white-space: pre;"></span>lpcbBytesReturned, NULL) );}char * CDiskInfo::ConvertToString (DWORD diskdata [256],<span style="white-space: pre;"></span>   int firstIndex,<span style="white-space: pre;"></span>   int lastIndex,<span style="white-space: pre;"></span>   char* buf){<span style="white-space: pre;"></span>int index = 0;<span style="white-space: pre;"></span>int position = 0;<span style="white-space: pre;"></span><span style="white-space: pre;"></span>//  each integer has two characters stored in it backwards<span style="white-space: pre;"></span>for (index = firstIndex; index <= lastIndex; index++)<span style="white-space: pre;"></span>{<span style="white-space: pre;"></span>//  get high byte for 1st character<span style="white-space: pre;"></span>buf [position++] = (char) (diskdata [index] / 256);<span style="white-space: pre;"></span><span style="white-space: pre;"></span>//  get low byte for 2nd character<span style="white-space: pre;"></span>buf [position++] = (char) (diskdata [index] % 256);<span style="white-space: pre;"></span>}<span style="white-space: pre;"></span><span style="white-space: pre;"></span>//  end the string <span style="white-space: pre;"></span>buf[position] = '\0';<span style="white-space: pre;"></span><span style="white-space: pre;"></span>//  cut off the trailing blanks<span style="white-space: pre;"></span>for (index = position - 1; index > 0 && isspace(buf [index]); index--)<span style="white-space: pre;"></span>buf [index] = '\0';<span style="white-space: pre;"></span><span style="white-space: pre;"></span>return buf;}char* CDiskInfo::GetHardDriveSerialNumber(){ <span style="white-space: pre;"></span>GetDeviceInfo();<span style="white-space: pre;"></span>char szbuf[1024]={0};<span style="white-space: pre;"></span>std::string strtemp = HardDriveSerialNumber; //去掉首尾空格<span style="white-space: pre;"></span>std::string strTemp2= trim(strtemp);<span style="white-space: pre;"></span>char* c;<span style="white-space: pre;"></span>const int len = strTemp2.length();<span style="white-space: pre;"></span>c = new char[len+1];   strcpy(c,strTemp2.c_str());<span style="white-space: pre;"></span>return c ;}char* CDiskInfo::GetHardDriveModelNumber(){<span style="white-space: pre;"></span><span style="white-space: pre;"></span>char* p=NULL;<span style="white-space: pre;"></span><span style="white-space: pre;"></span>GetDeviceInfo();<span style="white-space: pre;"></span>p = HardDriveModelNumber;<span style="white-space: pre;"></span>return p;}int CDiskInfo::GetComputerID(){<span style="white-space: pre;"></span><span style="white-space: pre;"></span>GetDeviceInfo();<span style="white-space: pre;"></span>return m_nID;}void CDiskInfo::GetDeviceInfo(){<span style="white-space: pre;"></span>int done = FALSE;<span style="white-space: pre;"></span>// char string [1024];<span style="white-space: pre;"></span>__int64 id = 0;<span style="white-space: pre;"></span>OSVERSIONINFO version;<span style="white-space: pre;"></span><span style="white-space: pre;"></span>strcpy (HardDriveSerialNumber, "");<span style="white-space: pre;"></span><span style="white-space: pre;"></span>memset (&version, 0, sizeof (version));<span style="white-space: pre;"></span>version.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);<span style="white-space: pre;"></span>GetVersionEx (&version);<span style="white-space: pre;"></span>if (version.dwPlatformId == VER_PLATFORM_WIN32_NT)<span style="white-space: pre;"></span>{<span style="white-space: pre;"></span>done = ReadPhysicalDriveInNTWithAdminRights ();<span style="white-space: pre;"></span>}<span style="white-space: pre;"></span>else<span style="white-space: pre;"></span>{<span style="white-space: pre;"></span>//  this works under Win9X and calls a VXD<span style="white-space: pre;"></span>// <span style="white-space: pre;"></span>int attempt = 0;<span style="white-space: pre;"></span>// <span style="white-space: pre;"></span><span style="white-space: pre;"></span>// <span style="white-space: pre;"></span>//  try this up to 10 times to get a hard drive serial number<span style="white-space: pre;"></span>// <span style="white-space: pre;"></span>for (attempt = 0;<span style="white-space: pre;"></span>// <span style="white-space: pre;"></span>attempt < 10 && ! done && 0 == HardDriveSerialNumber [0];<span style="white-space: pre;"></span>// <span style="white-space: pre;"></span>attempt++)<span style="white-space: pre;"></span>// <span style="white-space: pre;"></span>done = ReadDrivePortsInWin9X ();<span style="white-space: pre;"></span>}<span style="white-space: pre;"></span>if (HardDriveSerialNumber [0] > 0)<span style="white-space: pre;"></span>{<span style="white-space: pre;"></span>char *p = HardDriveSerialNumber;<span style="white-space: pre;"></span><span style="white-space: pre;"></span>WriteConstantString ("HardDriveSerialNumber", HardDriveSerialNumber);<span style="white-space: pre;"></span><span style="white-space: pre;"></span>//  ignore first 5 characters from western digital hard drives if<span style="white-space: pre;"></span>//  the first four characters are WD-W<span style="white-space: pre;"></span>if ( ! strncmp (HardDriveSerialNumber, "WD-W", 4)) <span style="white-space: pre;"></span>p += 5;<span style="white-space: pre;"></span>for ( ; p && *p; p++)<span style="white-space: pre;"></span>{<span style="white-space: pre;"></span>if ('-' == *p) <span style="white-space: pre;"></span>continue;<span style="white-space: pre;"></span>id *= 10;<span style="white-space: pre;"></span>switch (*p)<span style="white-space: pre;"></span>{            case '0': id += 0; break;            case '1': id += 1; break;            case '2': id += 2; break;            case '3': id += 3; break;            case '4': id += 4; break;            case '5': id += 5; break;            case '6': id += 6; break;            case '7': id += 7; break;            case '8': id += 8; break;            case '9': id += 9; break;            case 'a': case 'A': id += 10; break;            case 'b': case 'B': id += 11; break;            case 'c': case 'C': id += 12; break;            case 'd': case 'D': id += 13; break;            case 'e': case 'E': id += 14; break;            case 'f': case 'F': id += 15; break;            case 'g': case 'G': id += 16; break;            case 'h': case 'H': id += 17; break;            case 'i': case 'I': id += 18; break;            case 'j': case 'J': id += 19; break;            case 'k': case 'K': id += 20; break;            case 'l': case 'L': id += 21; break;            case 'm': case 'M': id += 22; break;            case 'n': case 'N': id += 23; break;            case 'o': case 'O': id += 24; break;            case 'p': case 'P': id += 25; break;            case 'q': case 'Q': id += 26; break;            case 'r': case 'R': id += 27; break;            case 's': case 'S': id += 28; break;            case 't': case 'T': id += 29; break;            case 'u': case 'U': id += 30; break;            case 'v': case 'V': id += 31; break;            case 'w': case 'W': id += 32; break;            case 'x': case 'X': id += 33; break;            case 'y': case 'Y': id += 34; break;            case 'z': case 'Z': id += 35; break;<span style="white-space: pre;"></span>}                            <span style="white-space: pre;"></span>}<span style="white-space: pre;"></span>}<span style="white-space: pre;"></span><span style="white-space: pre;"></span>id %= 100000000;<span style="white-space: pre;"></span>if (strstr (HardDriveModelNumber, "IBM-"))<span style="white-space: pre;"></span>id += 300000000;<span style="white-space: pre;"></span>else if (strstr (HardDriveModelNumber, "MAXTOR") ||<span style="white-space: pre;"></span>strstr (HardDriveModelNumber, "Maxtor"))<span style="white-space: pre;"></span>id += 400000000;<span style="white-space: pre;"></span>else if (strstr (HardDriveModelNumber, "WDC "))<span style="white-space: pre;"></span>id += 500000000;<span style="white-space: pre;"></span>else<span style="white-space: pre;"></span>id += 600000000;<span style="white-space: pre;"></span>m_nID = id;<span style="white-space: pre;"></span>char *pn = HardDriveSerialNumber;}DWORD CDiskInfo::GetMACaddress(void){<span style="white-space: pre;"></span>DWORD MACaddress = 0;<span style="white-space: pre;"></span>IP_ADAPTER_INFO AdapterInfo[16];       // Allocate information<span style="white-space: pre;"></span>// for up to 16 NICs<span style="white-space: pre;"></span>DWORD dwBufLen = sizeof(AdapterInfo);  // Save memory size of buffer<span style="white-space: pre;"></span><span style="white-space: pre;"></span>DWORD dwStatus = GetAdaptersInfo(      // Call GetAdapterInfo<span style="white-space: pre;"></span>AdapterInfo,                 // [out] buffer to receive data<span style="white-space: pre;"></span>&dwBufLen);                  // [in] size of receive data buffer<span style="white-space: pre;"></span>assert(dwStatus == ERROR_SUCCESS);  // Verify return value is<span style="white-space: pre;"></span>// valid, no buffer overflow<span style="white-space: pre;"></span><span style="white-space: pre;"></span>PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo; // Contains pointer to<span style="white-space: pre;"></span>// current adapter info<span style="white-space: pre;"></span>do {<span style="white-space: pre;"></span>if (MACaddress == 0)<span style="white-space: pre;"></span>MACaddress = pAdapterInfo->Address [5] + pAdapterInfo->Address [4] * 256 + <span style="white-space: pre;"></span>pAdapterInfo->Address [3] * 256 * 256 + <span style="white-space: pre;"></span>pAdapterInfo->Address [2] * 256 * 256 * 256;<span style="white-space: pre;"></span>PrintMACaddress(pAdapterInfo->Address); // Print MAC address<span style="white-space: pre;"></span>pAdapterInfo = pAdapterInfo->Next;    // Progress through linked list<span style="white-space: pre;"></span>}<span style="white-space: pre;"></span>while(pAdapterInfo);                    // Terminate if last adapter<span style="white-space: pre;"></span><span style="white-space: pre;"></span>return MACaddress;}char* CDiskInfo::GetMACAddressstring(){<span style="white-space: pre;"></span>GetMACaddress();<span style="white-space: pre;"></span>char *p = m_Macstring;<span style="white-space: pre;"></span>return p ;}std::string& trim(std::string &s) {    if (s.empty())     {        return s;    }<span style="white-space: pre;"></span>    s.erase(0,s.find_first_not_of(" "));    s.erase(s.find_last_not_of(" ") + 1);    return s;}

使用

#include "DiskInfo.h"void COPQRSTDlg::OnOK() {// TODO: Add extra validation hereCDiskInfo obj_DiskInfo;char szbuf[1024];char* buf=NULL;CString str1 = obj_DiskInfo.GetHardDriveSerialNumber();CString str2 = obj_DiskInfo.GetHardDriveModelNumber();int n = obj_DiskInfo.GetComputerID();CString str3 = obj_DiskInfo.GetMACAddressstring();CDialog::OnOK();}




0 0