linux下U盘序列号 C++
有没有办法使用 C++ 确定 Linux 中 USB 驱动器的序列号?
如果不是 C++,还有其他与 hwinfo -disk
和 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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我将尝试总结我在 Linux 上检索存储驱动器序列号的经验。
我假设您需要存储设备标识的序列号(根据SCSI规范)而不是USB设备的序列号(根据设备描述符 ),这两个是不同的实体。
驱动器分为 2 类(实际上更多,但让我们简化一下):类 ATA(hda、hdb ...)和类 SCSI(sda sdb ...)。
USB 驱动器属于第二类,它们称为SCSI 连接磁盘。
在这两种情况下,都可以使用 ioctl 调用来检索所需的信息(在我们的例子中是序列号) 。
对于 SCSI 设备(包括 USB 驱动器),Linux 通用驱动程序及其 API 记录在 tldp。
SCSI 设备上的序列号可在重要产品数据(简称:VPD)内找到,并且可检索通过使用 SCSI 查询命令。
Linux 中可以获取此 VPD 的命令行实用程序是 sdparm:
请注意,并非所有设备有了这个序列号,市场上充斥着廉价的仿冒品,并且一些 USB 闪存盘返回奇怪的序列号(例如我的 sandisk cruzer 仅返回字母“u”)。为了克服这个问题,有些人选择通过混合 VPD 中的不同字符串(例如产品 ID、供应商 ID 和序列号)来创建唯一标识符。
c 中的代码:
为了完整起见,我还将提供用于检索 ATA 设备(hda、hdb ...)序列号的代码。这不适用于 USB 设备。
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.
这段代码将获得 USB 序列号...它在技术上不如 clyfe 那样令人印象深刻,但似乎每次都能成功。
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.
我发现了一些你也感兴趣的东西:
“如何检测/dev/*是否是USB设备?"
I found something that would be also interesting for you:
"How to detect if /dev/* is a USB device?"
最好的方法可能是执行命令行工具(再次可能)执行的操作:检查
/proc
或/sys
中的相关文件,但要从 C++ 代码进行检查。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.