Get USB Drive Serial Number On Windows in C++
Get USB Drive Serial Number On Windows in C++
Get USB Drive Serial Number On Windows in C++
GetUSBDriveSerialNumberonWindowsinC++
PROGRAMMER'S
NOTEBOOK
Browse:HomeGetUSBDriveSerialNumberonWindowsinC++
GETUSBDRIVESERIALNUMBERON
WINDOWSINC++
June 1, 2012 by rafael in Programming
A B OU T M E
MynameisRafaelBaptista.I'ma
Bostonareatechnologyguy.
GettingtheserialnumberofaUSBdeviceinWindowsisalotharderthanitshouldbe.
I'mDirectorofSEOatKayak,a
(ButitsaloteasierthangettingtheUSBserialnumberonOsX!)
populartravelwebsite.I'malso
CTOofMimoco.Wemakecool
ItisrelativelysimpletogetUSBinformationifyouhavethedevicehandleoftheUSB
designerflashdrivesbasedon
deviceitself.Andyoucangetinformationaboutamountedvolumeprettyeasily.Butto
uniqueartistdesignsandpopular
matchupamountedvolumewithaUSBdeviceistrickyandannoying.
culturecharacters(likeStarWars,
HelloKittyandBatman).
TherearemanycodeexamplesonthenetabouthowtodoitinC#,visualbasic,and
similarbrokengarbagelanguages.IfyouareforcedtoprograminC#orvisualbasic
PreviouslyIwasanSEOanalyistat
gethelp.Therearealternativestosuicide.Therearesomeexampleofhowtodoit
TripAdvisor.FormanyyearsIwas
throughWMI,whichisaWindowsoperatingsystemservicewhichisslow,buggyand
agamedeveloper,helpingmake
unreliable.IfyouhavetodoitinWMI,youarebeyondhelp.
gamesforHarmonix,Apple,THQ,
LucasArts,Nickelodeon,Ubisoftand
Firsthereisthecode:
manyothers.I'veworkedon
speechrecognizersatKurzweil,
andgenomemappingatthe
#include<WinIOCtl.h>
#include<api/usbioctl.h>
#include<Setupapi.h>
DEFINE_GUID(GUID_DEVINTERFACE_USB_DISK,
0x53f56307L,0xb6bf,0x11d0,0x94,0xf2,
0x00,0xa0,0xc9,0x1e,0xfb,0x8b);
voidgetDeviceInfo(intvol)
{
UsbDeviceInfoinfo;
//getthedevicehandle
chardevicePath[7]="\\\\.\\@:";
devicePath[4]=(char)(vol+'A');
HANDLEdeviceHandle=CreateFile(devicePath,0,
FILE_SHARE_READ|
FILE_SHARE_WRITE,NULL,
OPEN_EXISTING,0,NULL);
if(deviceHandle==INVALID_HANDLE_VALUE)
return;
//togetthedevicenumber
DWORDvolumeDeviceNumber=getDeviceNumber(deviceHandle);
CloseHandle(deviceHandle);
https://oroboro.com/usbserialnumber/
MIT/WIBRHumanGenomeCenter.
S OCI A L
P ROJE CT S
1/11
6/12/2559
GetUSBDriveSerialNumberonWindowsinC++
Demangler.com
//Getdeviceinterfaceinfosethandle
AutomaticallydemanglesgccC++
//foralldevicesattachedtothesystem
HDEVINFOhDevInfo=SetupDiGetClassDevs(
symbols
&GUID_DEVINTERFACE_USB_DISK,NULL,NULL,
DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
RSZ.IO
if(hDevInfo==INVALID_HANDLE_VALUE)
Anonlineimageresizingservice
return;
//Getacontextstructureforthedeviceinterface
Unfurl
//ofadeviceinformationset.
BYTEBuf[1024];
AnonlinewebpagepreviewJSON
PSP_DEVICE_INTERFACE_DETAIL_DATApspdidd=
generator
(PSP_DEVICE_INTERFACE_DETAIL_DATA)Buf;
SP_DEVICE_INTERFACE_DATAspdid;
SP_DEVINFO_DATAspdd;
KJamBuildTool
spdid.cbSize=sizeof(spdid);
Abuildtoollikemakeorbjam
DWORDdwIndex=0;
while(true)
Anagramatik
{
if(!SetupDiEnumDeviceInterfaces(hDevInfo,NULL,
Ananagramwordgame,writtenin
&GUID_DEVINTERFACE_USB_DISK,
HTML5,crafty.jsandacustom
dwIndex,&spdid))
break;
serverapi.
DWORDdwSize=0;
SetupDiGetDeviceInterfaceDetail(hDevInfo,&spdid,NULL,
Herbarium
0,&dwSize,NULL);
Anexperimentinorganizingthe
if((dwSize!=0)&&(dwSize<=sizeof(Buf)))
datafortheSkyrimAlchemyskill
{
pspdidd>cbSize=sizeof(*pspdidd);//5Bytes!
MassachusettsElection2010
ZeroMemory((PVOID)&spdd,sizeof(spdd));
Anewssiteaboutthe2010election
spdd.cbSize=sizeof(spdd);
longres=SetupDiGetDeviceInterfaceDetail(
Cr0.me
hDevInfo,&spdid,pspdidd,
dwSize,&dwSize,&spdd);
AURLshortener
if(res)
{
HANDLEhDrive=CreateFile(pspdidd>DevicePath,0,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,OPEN_EXISTING,0,NULL);
if(hDrive!=INVALID_HANDLE_VALUE)
{
DWORDusbDeviceNumber=getDeviceNumber(hDrive);
if(usbDeviceNumber==volumeDeviceNumber)
{
fprintf("%s",pspdidd>DevicePath);
}
}
CloseHandle(hDrive);
}
}
dwIndex++;
}
SetupDiDestroyDeviceInfoList(hDevInfo);
return;
}
https://oroboro.com/usbserialnumber/
2/11
6/12/2559
GetUSBDriveSerialNumberonWindowsinC++
Youpassinthevolumenumber.Thisisjustthedriveletter,representedasaninteger.
DriveA:iszero.Sothefirstthingwedoiscreateadrivepath.Forexample,ifthe
mountedvolumeyouwanttogetaserialnumberforisF:,youdpassin5,and
constructadevicepath \\.\F: .
Nextyougetadevicehandleforthatvolumeusing CreateFile() .Originallythisfunction
wasmeanttocreateregularfilesystemfiles.Buttodayitcanbeusedtoopenhandles
todevicesofallkinds.Eachdevicetypeisrepresentedbydifferentdevicepaths.
Next,yougetthedevicenumber.Whenavolumeismounted,itwillbeassociatedwith
adevice,andthisfunctionreturnsitsnumber.WhytheOSdoesntjustgiveyoua
devicepathhereisridiculous.Thedevicenumberswillbelow.Typicallyanumber
under10.Dontbesurprised.Iwas.
Yougetthedevicenumberbycalling DeviceIOControl() withthehandletoyourdevice:
DWORDgetDeviceNumber(HANDLEdeviceHandle)
{
STORAGE_DEVICE_NUMBERsdn;
sdn.DeviceNumber=1;
DWORDdwBytesReturned=0;
if(!DeviceIoControl(deviceHandle,
IOCTL_STORAGE_GET_DEVICE_NUMBER,
NULL,0,&sdn,sizeof(sdn),
&dwBytesReturned,NULL))
{
//handleerrorlikeabadhandle.
returnU32_MAX;
}
returnsdn.DeviceNumber;
}
Thenforeachdeviceyougetthedevicenameandnumberusing
SetupDiGetDeviceInterfaceDetail ,andmatchupthedevicenumberofeachdevicewiththe
oneyougotforthevolume.Whenyoufindamatchthenyouhavethedevicepathfor
youractualUSBflashdrive.Atthatpointyoucouldstartqueryingthedeviceitselfusing
functionslike DeviceIoControl() ,butinthiscasetheinformationwewantiscodedright
intothedevicepath
https://oroboro.com/usbserialnumber/
3/11
6/12/2559
GetUSBDriveSerialNumberonWindowsinC++
HereisatypicaldevicepathforaUSBflashdisk:
\\?\usbstor#disk&ven_cbm&prod_flash_disk&rev_5.00#31120000dc0ce201&0#
{53f56307b6bf11d094f200a0c91efb8b}
Thedevicepathforaflashdiskmuststartwithusbstor.Thisfirstpartofthepathis
nameofthedriver,whichonwindowsiscalledusbstor.Thevendorid,productid,
productrevisionandserialnumberarehighlightedinred.
Thefollowingregularexpressionswillextractthisinformationfromthedevicepath:
ven_([^&#]+)//vendorid
prod_([^&#]+)//productid
rev_([^&#]+)//revisionid
&[^#]*#([^&#]+)//serialnumber
Nexthereisamethodtorecognizeifavolumeisremovablemedia(e.g.likeausbor
firewiredisk):
boolisRemovableMedia(s32vol)
{
charrootPath[5]="@:\\";
rootPath[0]=(char)(vol+'A');
charszDosDeviceName[MAX_PATH];
chardosDevicePath[3]="@:";
//getthedrivetype
UINTDriveType=GetDriveType(rootPath);
if(DriveType!=DRIVE_REMOVABLE)
returnfalse;
dosDevicePath[0]=(char)(vol+'A');
QueryDosDevice(dosDevicePath,szDosDeviceName,MAX_PATH);
if(strstr(szDosDeviceName,"\\Floppy")!=NULL)
{
//itsafloppy
returnfalse;
}
returntrue;
}
Resources:
CreateFilefunction
MSDNReferenceforCreateFile
SetupDiEnumDeviceInterfaces
MSDNReferencefor
https://oroboro.com/usbserialnumber/
4/11
6/12/2559
GetUSBDriveSerialNumberonWindowsinC++
function
SetupDiEnumDeviceInterfaces
GetDriveTypefunction
MSDNReferenceforGetDriveType
DeviceIoControlfunction
MSDNRefenceforDeviceIoControl
DeviceIoControlfunction
MSDNRefenceforDeviceIoControl
HowtogettheSerialNumber
SerialNumbercodeexamplesinWMIandVisual
fromaUSBdisk
Basic
WindowsDriverKit(WDK)
Thewindowsdevicedrivertoolkit.Hasheaders
youmayneed
FlashMemoryToolkit
Aprogramtoviewtheserialnumber,for
debugging
DiskId32
Includesalinktoacodeexamplethatgetsserial
numbersfromharddisks
HowtoPrepareaUSBDrive
Showsasimilarmethodformappingvolumesto
forSafeRemoval
USBDevices
Tags:c++,USB,win32
19Responses
kumarAugust2,2012at23:26:38
Goodarticle,thanks.
Canyouprovidec++codeusingregularexpressionstoextracttheserial
number?
rafaelAugust2,2012at23:36:11
Iusemyownregularexpressionclass,andtoworkitrequiresa
wholebunchofmysupportinglibraries,soitwouldntmakesense
topostithere.
IknowthattheSTLnowsupportsregularexpressions.Try #include
<regexp> ,andusingthe regexp class.
https://oroboro.com/usbserialnumber/
5/11
6/12/2559
GetUSBDriveSerialNumberonWindowsinC++
Thereisatutorialonithere:
http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15339/A
TR1TutorialRegularExpressions.htm
TsumeAugust3,2012at22:31:36
WhatiftheUSBdeviceisnotadrive?Whatifitsamouse?Oriseverything
onUSBhandledasadrive?Withoutgoingintoallthegorydetails,Ihave
putsomeadditionalcircuitryintoanoldUSBmousetomonitorsome
externaleventsbywhetherthecomputerdetectstheoldmouseornot.
Now,allIneedisthesoftwarecomponent,underWindows,thatwould
monitorthatoldmouse.Ofcourse,thethingis,Ineedtomakesurethe
programmonitorstheCORRECTUSBdevice.AnotherproblemisthatIama
Unix/Linuxperson(andcoulddothiswithasimplescriptunderLinux),but
thisaspectofWindowsisanalienenvironmentforme.Ihaveinstalledthe
freeVisualC++Express,andwhatyoumentionedinyourarticlesounds
good,butIdontknowifIllbeabletoapplyittoamouse,insteadofa
drive.
Whatdoyouthink?
JBOctober16,2012at02:17:34
Excellentpost!Howtogoaboutgettingtheserialnumberofafixeddisk
drive?Thanks.
CoreyVelanNovember7,2012at15:49:24
Greatpost!OnequestionwhereisgetDeviceNumberdefined?Icantget
thistocompilebecauseofthatfunction.
rafaelNovember7,2012at16:29:31
Thatisoneofmyownfunctions.Illupdatethearticlewiththe
implementationforthat.Butitsprettysimpleyougetitfromacallto
DeviceIOControl.
mikeNovember19,2012at20:33:46
https://oroboro.com/usbserialnumber/
6/11
6/12/2559
GetUSBDriveSerialNumberonWindowsinC++
selectDeviceIDfromWin32_USBHubwhereName=USBMassStorage
Device
IfoundonmyUSBdrives,thisstringincludesauniqueidforthedrive.
reshmaDecember11,2012at13:29:22
howtoincludethethreeheaderfiles..
#include
#include
#include
ididntfindanysourceforthesethreefiles..
pleasehelpme
rafaelDecember11,2012at23:54:15
Doyoumeanthethreeheadersfromthefirstcodelisting?Like
WinIOCtl.h?Thesearestandardwindowsheaderfiles.You
shouldhavethemifyouinstallMicrosoftsc++compiler(Visual
Studio).Itcomeswiththewindowsplatformsdk.Theseshouldbe
includedwiththat.
NormanDiamondOctober23,2013at05:38:17
#include
comesfromtheWindowsDriverKit,notfromVisualStudio.
ReshmashoulddownloadtheWDKfromthelinkthatyou
gave.
TheothertwoareintheSDK.
NormanDiamondOctober23,2013at05:41:40
AlthoughyourGUIDiscorrect,youdonthavetodoit.
DEFINE_GUID(GUID_DEVINTERFACE_USB_DISK,
0x53f56307L,0xb6bf,0x11d0,0x94,0xf2,
0x00,0xa0,0xc9,0x1e,0xfb,0x8b)
Instead,youcangetitfromtheWDK.
TousetheWDK,thislooksredundantbutyouhavetodoitthisway.
#includeap/\Ntddstor.h
https://oroboro.com/usbserialnumber/
7/11
6/12/2559
GetUSBDriveSerialNumberonWindowsinC++
#includeinitguid.h
#includeapi/Ntddstor.h
NormanDiamondOctober23,2013at05:42:55
UsbDeviceInfoinfo
isntneeded.Inordertocompile,justdeleteit^_^
NormanDiamondOctober23,2013at05:45:31
Iwilltrytocorrectaneditingerrorinmypreviousreply.
Iftheownereditsmypreviousreplyanddeletesthisone,thatwillbegood.
#includeapi/Ntddstor.h
#includeinitguid.h
#includeapi/Ntddstor.h
(TheredundancyisthatNtddstor.hhastobeincludedtwice.Thepathname
shouldntbemesseduplikeIdid.)
NormanDiamondOctober23,2013at05:50:05
Sorry,Ihavetoeditthisagain.
Afterthis:
#includeapi/Ntddstor.h
#includeinitguid.h
#includeapi/Ntddstor.h
Use
GUID_DEVINTERFACE_DISK
insteadof
GUID_DEVINTERFACE_USB_DISK
NormanDiamondNovember10,2013at17:45:59
Inthedeviceinfoinyourexample,Windowshassetthedevicesserial
numberto
31120000dc0ce201
Ibetthedevicesactualserialnumbermightbe
31120000DC0CE201
https://oroboro.com/usbserialnumber/
8/11
6/12/2559
GetUSBDriveSerialNumberonWindowsinC++
WindowsscaseinsensivityisOKforWindows,butitmightnotbeOKfor
someapplicationthatneedstoknowtherealserialnumber.
ActuallyWindowsdidmorethanjustbecaseinsensitive.Infilenames,
Windowsiscaseinsensitiveinmatchingnames,butwhenwritingnamesin
thefirstplaceitpreservesthecasethattheuserusedwhencreatingthe
file.IfyoulookinWindowsExploreroradircommand,YouCANStillSee
NamesliketHis.ButWindowsgivesusthedevicesserialnumberasifit
werealllowercase.
Doesanyoneknowhowtofindtherealserialnumber?
EricNovember21,2013at04:21:54
CanthiscodeworkinWindows8.1MetroStyleapp?
hemalvadgamaJanuary2,2015at08:25:59
Couldnotgetthistowork,doyouhavethesourcecode?Igetalnk2019
errormaybeifaliedtoaddsomelibs?
arvindhFebruary12,2015at01:29:33
Iwastryingthesameonpython,.whenisawyourpost,itriedtocompileit
(Iamnewtoallprogramming,iinstalledmingw)withthiscommand
g++findserial.cppofindserial.out
igetthisfollowingerror
findserial.cpp:2:26:fatalerror:api/usbioctl.h:Nosuchfileordirectory
compilationterminated.
cananyonepleasehelp
keekMay20,2015at08:08:29
Incaseyouneedtheserialnumbertobecasesensitive,youcanutilizethe
followingcodetoextractitfromtheregistry.
TheparameterusbDeviceIdisexpectedtobeintheformat
USB\\VID_XXXX&PID_XXXXandcanbeobtainedusing
CM_Get_Device_ID.
https://oroboro.com/usbserialnumber/
9/11
6/12/2559
GetUSBDriveSerialNumberonWindowsinC++
AlthoughmyexampleusesQtitmighthelp:
QStringExtractSerialNumberFromRegistry(constQString&usbDeviceId)
{
QStringserial
QStringListparts=usbDeviceId.split(\\)
if(parts.size()==3)
{
QStringparentNode(SYSTEM\\CurrentControlSet\\Enum\\%1\\%2)
HKEYhKey
longresult=RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
reinterpret_cast(parentNode.arg(parts.at(0)).arg(parts.at(1)).utf16()),
0,
KEY_READ,
&hKey)
if(result==ERROR_SUCCESS)
{
wchar_t*subkey=newwchar_t[255]
DWORDsubkey_length=255
DWORDcounter=0
while(result!=ERROR_NO_MORE_ITEMS)
{
result=RegEnumKeyEx(hKey,counter,subkey,&subkey_length,0,NULL,
NULL,NULL)
if(result==ERROR_SUCCESS)
{
//findbestmatchusingtheuppercaseserialnestedintheusbdeviceid
constQStringcurrSerial(reinterpret_cast(subkey))
if(result==ERROR_SUCCESS&&parts.last().toUpper()==
currSerial.toUpper())
serial=currSerial
}
https://oroboro.com/usbserialnumber/
10/11
6/12/2559
GetUSBDriveSerialNumberonWindowsinC++
++counter
}
deletesubkey
subkey=0
RegCloseKey(hKey)
}
}
returnserial
}
LeaveaReply
Name*
Email*
Website
PostComment
PseudoFunctorsandTemplateMagic
OverloadingGlobaloperatornewanddelete
Copyright2016Programmer'sNotebook
PoweredbyWordPressandOrigin
https://oroboro.com/usbserialnumber/
11/11