I was wondering how to get the unique id of a USB storage device. I already know how to fetch the SCSI serial id from this post : USB-drive serial number under linux C++ Th
With USB, the "device name" of a device can change, depending on the order of which, the device was connected. Surprisingly few devices have a real serial number. If you can't get a unique identification from the device itself, the only solution is to depend on the physical address of connection. The drawback on this, is that the address changes, if you plug the device into another USB connector.
Programmatically you can use sysfs to get the information the kernel has, about the device. Sysfs is a file-system-like representation of devices as the kernel sees them. (Its not real files on the disk)
With it, you can: - identify the device type with product and vendor ID - read the serial number of the device, if it has one. - read the physical connection number on the USB hub
You could start by finding your type of devices in /sys/class. In this example I use an USB→LPT port. But the principle is the same.
$ ls -l /sys/class/usbmisc
lp1 -> ../../devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.5/4-1.5:1.0/usbmisc/lp1
lp2 -> ../../devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.6/4-1.6:1.0/usbmisc/lp2
Grap the device name from the uevent file:
cat /sys/class/usbmisc/lp1/uevent
MAJOR=180
MINOR=1
DEVNAME=__usb/lp1__
add /dev so you get the device name to open: /dev/usb/lp1
Use the real path: $ cd -P /sys/class/usbmisc/lp1
Step back 3 branches:
$ cd ../../../
/sys/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.5
This directory contains a lot of the information on the device:
idProduct and idVendor can be used to uniquely identify the device type.
If there is a serial file and it contains a unique serial number, you are done.
Otherwise your option is to use the physical connection as identification, wich is this directory name “4-1.5” It is unique for the physical connection, and will as you already mentioned change if you plug the device to another port.