Is there any way to determine s/n of usb-drive in linux using C++ ?
If not C++ is there any other way different from hwinfo -disk
and hdparm -i
?
Is there any way to determine s/n of usb-drive in linux using C++ ?
If not C++ is there any other way different from hwinfo -disk
and hdparm -i
?
And this piece of code will get the USB serial number... it's not as technically impressive as clyfe's, but it seems to do the trick every time.
I found something that would be also interesting for you:
"How to detect if /dev/* is a USB device?"
The best way is probably to do what the command-line tools (again, probably) do: inspect the relevant files in either
/proc
or/sys
, but from C++ code.I'll try to summarize my experience regarding storage drive serial number retrieval on linux.
I assume you want the serial number of the storage device identity (as per SCSI specification) not the serial number of the USB device (as per USB specification under Device Descriptor ), these two are different entities.
Drives fall in 2 categories (actually more, but let's simplify): ATA-like (hda, hdb ...) and SCSI-like (sda sdb ...). USB drives fall in the second category, they are called SCSI attached disks. In both situation ioctl calls can be used to retrieve the required information (in our case the serial number).
For SCSI devices (and these include USB drives) the Linux generic driver and it's API is documented at tldp.
The serial number on SCSI devices is available inside the Vital Product Data (short: VPD) and is retrievable by using the SCSI Inquiry Command. A commad line utility in linux that can fetch this VPD is sdparm:
Note that not all devices have this serial number, the market is flooded with cheep knockoffs, and some usb flash disks return strange serials (for example my sandisk cruzer returns just the letter "u"). To overcome this some people choose to create a unique identifier by mixing different strings from VPD like Product ID, Vendor ID and Serial Number.
Code in c:
For the sake of completness i'll also provide the code to retrieve the serial number for ATA devices (hda, hdb ...). This will NOT work for USB devices.