I'm trying to retrieve the serial number of a hard drive or a battery tag

546 views Asked by At
#include "stdafx.h"
#include <stdio.h> 
#include <stdlib.h>
#include <windows.h>
#include <string.h>
#include <process.h>
#include <WinIoCtl.h>
#include <Winbase.h>

typedef struct _MEDIA_SERIAL_NUMBER_DATA {  
      ULONG SerialNumberLength;
      ULONG Result;
      ULONG Retreived;
      DWORD SerialNumberData[];
} MEDIA_SERIAL_NUMBER_DATA, *PMEDIA_SERIAL_NUMBER_DATA;  // the structure of IOCTL_MEDIA_SERIAL_NUMBER_DATA 

int main() {
    HANDLE hard;
    bool result;
    MEDIA_SERIAL_NUMBER_DATA  val;  
    char buf[sizeof(MEDIA_SERIAL_NUMBER_DATA)];
    MEDIA_SERIAL_NUMBER_DATA * p = (MEDIA_SERIAL_NUMBER_DATA *) buf;

    hard = CreateFile(L"\\\\.\\C:", 0, FILE_SHARE_WRITE, NULL,    OPEN_EXISTING, 0, 0);
    result = DeviceIoControl(hard, IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER,    NULL, 0, buf, sizeof buf, 0, NULL);

   if (hard == INVALID_HANDLE_VALUE) 
       printf("Terminal error : invalid handle value \n");

   printf("valeur Handle : %c \n", hard);
   printf("valeur retour :    %d \n", result);
   printf("valeur serial : %d \n",    p->SerialNumberData);     
   printf("valeur longeur num serie : %d \n",    p->SerialNumberLength); 

   CloseHandle(hard); // free the Handle    
   system("pause");
   return 0;
}

When I compile and execute this piece of code, I get following result:

valeur Handle : D
valeur retour : 0
valeur serial : 15530164     
valeur longeur num serie : -858993460
1

There are 1 answers

1
molbdnilo On BEST ANSWER

Consider reading some documentation.

  1. Almost all your printfs use the wrong format string.
  2. Your structure is not the structure that DeviceIoControl returns for IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER.
  3. If lpOverlapped is NULL, lpBytesReturned cannot be NULL.
  4. IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER retrieves the serial number of a USB device.
  5. The return value zero from DeviceIoControl indicates failure.