⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 diskid32.cpp

📁 DiskId32最新版 在NT/2000/XP/2003/VISTA下取PATA/SATA/SCSI)下支持获取硬盘的系列号。 编译需要Windows SDK
💻 CPP
📖 第 1 页 / 共 4 页
字号:
      sprintf (driveName, "\\\\.\\PhysicalDrive%d", drive);         //  Windows NT, Windows 2000, Windows XP - admin rights not required      hPhysicalDriveIOCTL = CreateFile (driveName, 0,                               FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,                               OPEN_EXISTING, 0, NULL);      if (hPhysicalDriveIOCTL == INVALID_HANDLE_VALUE)      {#ifdef PRINTING_TO_CONSOLE_ALLOWED         if (PRINT_DEBUG)             printf ("\n%d ReadPhysicalDriveInNTWithZeroRights ERROR"		             "\nCreateFile(%s) returned INVALID_HANDLE_VALUE\n",		             __LINE__, driveName);#endif      }      else      {		 STORAGE_PROPERTY_QUERY query;         DWORD cbBytesReturned = 0;		 char buffer [10000];         memset ((void *) & query, 0, sizeof (query));		 query.PropertyId = StorageDeviceProperty;		 query.QueryType = PropertyStandardQuery;		 memset (buffer, 0, sizeof (buffer));         if ( DeviceIoControl (hPhysicalDriveIOCTL, IOCTL_STORAGE_QUERY_PROPERTY,                   & query,                   sizeof (query),				   & buffer,				   sizeof (buffer),                   & cbBytesReturned, NULL) )         {         			 STORAGE_DEVICE_DESCRIPTOR * descrip = (STORAGE_DEVICE_DESCRIPTOR *) & buffer;			 char serialNumber [1000];			 char modelNumber [1000];             char vendorId [1000];	         char productRevision [1000];#ifdef PRINTING_TO_CONSOLE_ALLOWED             if (PRINT_DEBUG)             {                 printf ("\n%d STORAGE_DEVICE_DESCRIPTOR contents for drive %d\n"		                 "                Version: %ld\n"		                 "                   Size: %ld\n"		                 "             DeviceType: %02x\n"		                 "     DeviceTypeModifier: %02x\n"		                 "         RemovableMedia: %d\n"		                 "        CommandQueueing: %d\n"		                 "         VendorIdOffset: %4ld (0x%02lx)\n"		                 "        ProductIdOffset: %4ld (0x%02lx)\n"		                 "  ProductRevisionOffset: %4ld (0x%02lx)\n"		                 "     SerialNumberOffset: %4ld (0x%02lx)\n"		                 "                BusType: %d\n"		                 "    RawPropertiesLength: %ld\n",		                 __LINE__, drive,			             (unsigned long) descrip->Version,		                 (unsigned long) descrip->Size,		                 (int) descrip->DeviceType,		                 (int) descrip->DeviceTypeModifier,		                 (int) descrip->RemovableMedia,		                 (int) descrip->CommandQueueing,		                 (unsigned long) descrip->VendorIdOffset,		                 (unsigned long) descrip->VendorIdOffset,		                 (unsigned long) descrip->ProductIdOffset,		                 (unsigned long) descrip->ProductIdOffset,		                 (unsigned long) descrip->ProductRevisionOffset,		                 (unsigned long) descrip->ProductRevisionOffset,		                 (unsigned long) descrip->SerialNumberOffset,		                 (unsigned long) descrip->SerialNumberOffset,		                 (int) descrip->BusType,		                 (unsigned long) descrip->RawPropertiesLength);	            dump_buffer ("Contents of RawDeviceProperties",			                 (unsigned char*) descrip->RawDeviceProperties,			                 descrip->RawPropertiesLength);	            dump_buffer ("Contents of first 256 bytes in buffer",			                 (unsigned char*) buffer, 256);			 }#endif             flipAndCodeBytes (buffer,                               descrip -> VendorIdOffset,			                   0, vendorId );	         flipAndCodeBytes (buffer,			                   descrip -> ProductIdOffset,			                   0, modelNumber );	         flipAndCodeBytes (buffer,			                   descrip -> ProductRevisionOffset,			                   0, productRevision );	         flipAndCodeBytes (buffer,			                   descrip -> SerialNumberOffset,			                   1, serialNumber );			 if (0 == HardDriveSerialNumber [0] &&						//  serial number must be alphanumeric			            //  (but there can be leading spaces on IBM drives)				   (isalnum (serialNumber [0]) || isalnum (serialNumber [19])))			 {				strcpy (HardDriveSerialNumber, serialNumber);				strcpy (HardDriveModelNumber, modelNumber);				done = TRUE;			 }#ifdef PRINTING_TO_CONSOLE_ALLOWED             printf ("\n**** STORAGE_DEVICE_DESCRIPTOR for drive %d ****\n"		             "Vendor Id = [%s]\n"		             "Product Id = [%s]\n"		             "Product Revision = [%s]\n"		             "Serial Number = [%s]\n",		             drive,		             vendorId,		             modelNumber,		             productRevision,		             serialNumber);#endif	           // Get the disk drive geometry.	         memset (buffer, 0, sizeof(buffer));	         if ( ! DeviceIoControl (hPhysicalDriveIOCTL,			          IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,			          NULL,			          0,			          &buffer,			          sizeof(buffer),			          &cbBytesReturned,			          NULL))	         {#ifdef PRINTING_TO_CONSOLE_ALLOWED                if (PRINT_DEBUG)	               printf ("\n%d ReadPhysicalDriveInNTWithZeroRights ERROR"		                   "|nDeviceIoControl(%s, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX) returned 0",		                   driveName);#endif          	 }	         else	         {         	            DISK_GEOMETRY_EX* geom = (DISK_GEOMETRY_EX*) &buffer;	            int fixed = (geom->Geometry.MediaType == FixedMedia);	            __int64 size = geom->DiskSize.QuadPart;				     #ifdef PRINTING_TO_CONSOLE_ALLOWED	            printf ("\n**** DISK_GEOMETRY_EX for drive %d ****\n"		                "Disk is%s fixed\n"		                "DiskSize = %I64d\n",		                drive,		                fixed ? "" : " NOT",		                size);#endif	        }         }		 else		 {			 DWORD err = GetLastError ();#ifdef PRINTING_TO_CONSOLE_ALLOWED			 printf ("\nDeviceIOControl IOCTL_STORAGE_QUERY_PROPERTY error = %d\n", err);#endif		 }         CloseHandle (hPhysicalDriveIOCTL);      }   }   return done;}   // DoIDENTIFY   // FUNCTION: Send an IDENTIFY command to the drive   // bDriveNum = 0-3   // bIDCmd = IDE_ATA_IDENTIFY or IDE_ATAPI_IDENTIFYBOOL DoIDENTIFY (HANDLE hPhysicalDriveIOCTL, PSENDCMDINPARAMS pSCIP,                 PSENDCMDOUTPARAMS pSCOP, BYTE bIDCmd, BYTE bDriveNum,                 PDWORD lpcbBytesReturned){      // Set up data structures for IDENTIFY command.   pSCIP -> cBufferSize = IDENTIFY_BUFFER_SIZE;   pSCIP -> irDriveRegs.bFeaturesReg = 0;   pSCIP -> irDriveRegs.bSectorCountReg = 1;   //pSCIP -> irDriveRegs.bSectorNumberReg = 1;   pSCIP -> irDriveRegs.bCylLowReg = 0;   pSCIP -> irDriveRegs.bCylHighReg = 0;      // Compute the drive number.   pSCIP -> irDriveRegs.bDriveHeadReg = 0xA0 | ((bDriveNum & 1) << 4);      // The command can either be IDE identify or ATAPI identify.   pSCIP -> irDriveRegs.bCommandReg = bIDCmd;   pSCIP -> bDriveNumber = bDriveNum;   pSCIP -> cBufferSize = IDENTIFY_BUFFER_SIZE;   return ( DeviceIoControl (hPhysicalDriveIOCTL, DFP_RECEIVE_DRIVE_DATA,               (LPVOID) pSCIP,               sizeof(SENDCMDINPARAMS) - 1,               (LPVOID) pSCOP,               sizeof(SENDCMDOUTPARAMS) + IDENTIFY_BUFFER_SIZE - 1,               lpcbBytesReturned, NULL) );}//  ---------------------------------------------------   // (* Output Bbuffer for the VxD (rt_IdeDinfo record) *)typedef struct _rt_IdeDInfo_{    BYTE IDEExists[4];    BYTE DiskExists[8];    WORD DisksRawInfo[8*256];} rt_IdeDInfo, *pt_IdeDInfo;   // (* IdeDinfo "data fields" *)typedef struct _rt_DiskInfo_{   BOOL DiskExists;   BOOL ATAdevice;   BOOL RemovableDevice;   WORD TotLogCyl;   WORD TotLogHeads;   WORD TotLogSPT;   char SerialNumber[20];   char FirmwareRevision[8];   char ModelNumber[40];   WORD CurLogCyl;   WORD CurLogHeads;   WORD CurLogSPT;} rt_DiskInfo;#define  m_cVxDFunctionIdesDInfo  1//  ---------------------------------------------------int ReadDrivePortsInWin9X (void){   int done = FALSE;   unsigned long int i = 0;   HANDLE VxDHandle = 0;   pt_IdeDInfo pOutBufVxD = 0;   DWORD lpBytesReturned = 0;		//  set the thread priority high so that we get exclusive access to the disk   BOOL status =		// SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);		SetPriorityClass (GetCurrentProcess (), REALTIME_PRIORITY_CLASS);		// SetPriorityClass (GetCurrentProcess (), HIGH_PRIORITY_CLASS);#ifdef PRINTING_TO_CONSOLE_ALLOWED   if (0 == status) 	   // printf ("\nERROR: Could not SetThreadPriority, LastError: %d\n", GetLastError ());	   printf ("\nERROR: Could not SetPriorityClass, LastError: %d\n", GetLastError ());#endif      // 1. Make an output buffer for the VxD   rt_IdeDInfo info;   pOutBufVxD = &info;      // *****************      // KLUDGE WARNING!!!      // HAVE to zero out the buffer space for the IDE information!      // If this is NOT done then garbage could be in the memory      // locations indicating if a disk exists or not.   ZeroMemory (&info, sizeof(info));      // 1. Try to load the VxD       //  must use the short file name path to open a VXD file   //char StartupDirectory [2048];   //char shortFileNamePath [2048];   //char *p = NULL;   //char vxd [2048];      //  get the directory that the exe was started from   //GetModuleFileName (hInst, (LPSTR) StartupDirectory, sizeof (StartupDirectory));      //  cut the exe name from string   //p = &(StartupDirectory [strlen (StartupDirectory) - 1]);   //while (p >= StartupDirectory && *p && '\\' != *p) p--;   //*p = '\0';      //GetShortPathName (StartupDirectory, shortFileNamePath, 2048);   //sprintf (vxd, "\\\\.\\%s\\IDE21201.VXD", shortFileNamePath);   //VxDHandle = CreateFile (vxd, 0, 0, 0,   //               0, FILE_FLAG_DELETE_ON_CLOSE, 0);      VxDHandle = CreateFile ("\\\\.\\IDE21201.VXD", 0, 0, 0,							0, FILE_FLAG_DELETE_ON_CLOSE, 0);   if (VxDHandle != INVALID_HANDLE_VALUE)   {         // 2. Run VxD function      DeviceIoControl (VxDHandle, m_cVxDFunctionIdesDInfo,					0, 0, pOutBufVxD, sizeof(pt_IdeDInfo), &lpBytesReturned, 0);         // 3. Unload VxD      CloseHandle (VxDHandle);   }   else		MessageBox (NULL, "ERROR: Could not open IDE21201.VXD file", 					TITLE, MB_ICONSTOP);      // 4. Translate and store data   for (i=0; i<8; i++)   {      if((pOutBufVxD->DiskExists[i]) && (pOutBufVxD->IDEExists[i/2]))      {			DWORD diskinfo [256];			for (int j = 0; j < 256; j++) 				diskinfo [j] = pOutBufVxD -> DisksRawInfo [i * 256 + j];            // process the information for this buffer		   PrintIdeInfo (i, diskinfo);			done = TRUE;      }   }		//  reset the thread priority back to normal   // SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_NORMAL);   SetPriorityClass (GetCurrentProcess (), NORMAL_PRIORITY_CLASS);   return done;}#define  SENDIDLENGTH  sizeof (SENDCMDOUTPARAMS) + IDENTIFY_BUFFER_SIZEint ReadIdeDriveAsScsiDriveInNT (void){   int done = FALSE;   int controller = 0;   for (controller = 0; controller < 16; controller++)   {      HANDLE hScsiDriveIOCTL = 0;      char   driveName [256];         //  Try to get a handle to PhysicalDrive IOCTL, report failure         //  and exit if can't.      sprintf (driveName, "\\\\.\\Scsi%d:", controller);         //  Windows NT, Windows 2000, any rights should do      hScsiDriveIOCTL = CreateFile (driveName,                               GENERIC_READ | GENERIC_WRITE,                                FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,                               OPEN_EXISTING, 0, NULL);      // if (hScsiDriveIOCTL == INVALID_HANDLE_VALUE)      //    printf ("Unable to open SCSI controller %d, error code: 0x%lX\n",      //            controller, GetLastError ());      if (hScsiDriveIOCTL != INVALID_HANDLE_VALUE)      {         int drive = 0;         for (drive = 0; drive < 2; drive++)         {            char buffer [sizeof (SRB_IO_CONTROL) + SENDIDLENGTH];            SRB_IO_CONTROL *p = (SRB_IO_CONTROL *) buffer;            SENDCMDINPARAMS *pin =                   (SENDCMDINPARAMS *) (buffer + sizeof (SRB_IO_CONTROL));            DWORD dummy;               memset (buffer, 0, sizeof (buffer));            p -> HeaderLength = sizeof (SRB_IO_CONTROL);            p -> Timeout = 10000;            p -> Length = SENDIDLENGTH;            p -> ControlCode = IOCTL_SCSI_MINIPORT_IDENTIFY;            strncpy ((char *) p -> Signature, "SCSIDISK", 8);              pin -> irDriveRegs.bCommandReg = IDE_ATA_IDENTIFY;            pin -> bDriveNumber = drive;            if (DeviceIoControl (hScsiDriveIOCTL, IOCTL_SCSI_MINIPORT,                                  buffer,                                 sizeof (SRB_IO_CONTROL) +                                         sizeof (SENDCMDINPARAMS) - 1,                                 buffer,                                 sizeof (SRB_IO_CONTROL) + SENDIDLENGTH,                                 &dummy, NULL))            {               SENDCMDOUTPARAMS *pOut =                    (SENDCMDOUTPARAMS *) (buffer + sizeof (SRB_IO_CONTROL));               IDSECTOR *pId = (IDSECTOR *) (pOut -> bBuffer);               if (pId -> sModelNumber [0])               {                  DWORD diskdata [256];                  int ijk = 0;                  USHORT *pIdSector = (USHORT *) pId;                            for (ijk = 0; ijk < 256; ijk++)                     diskdata [ijk] = pIdSector [ijk];                  PrintIdeInfo (controller * 2 + drive, diskdata);                  done = TRUE;               }            }         }         CloseHandle (hScsiDriveIOCTL);      }   }   return done;}void PrintIdeInfo (int drive, DWORD diskdata [256]){

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -