Linux下C++获取USB驱动器序列号

11

有没有一种在Linux下使用C++确定USB驱动器的序列号的方法?

如果不是用C++,是否有与 hwinfo -diskhdparm -i 不同的其他方法?

4个回答

24
我将尝试总结有关Linux上存储驱动器序列号检索的经验。 我假设您想要获取存储设备标识的序列号(根据SCSI规范),而不是USB设备的序列号(根据Device Descriptor下的USB规范),这两个实体是不同的。
注意!大多数设备倾向于在USB控制器中实现序列号,并未实现内部SCSI磁盘的序列号。因此,如果您想唯一地识别USB设备,则最好从Device Descriptor(USB规范)创建一个字符串,例如VendorId-ProductId-HardwareRevision-SerialNumber。接下来,我将描述如何检索所需信息(在我们的情况下为序列号)。
驱动器分为两类(实际上更多,但让我们简化):类似ATA(hda,hdb ...)和类似SCSI(sda sdb ...)。 USB驱动器属于第二类,称为SCSI附加磁盘。在这两种情况下,可以使用ioctl调用来检索所需的信息(在我们的情况下为序列号)。
对于SCSI设备(包括USB驱动器),Linux通用驱动程序及其API的文档记录在tldp中。
SCSI设备上的序列号可以在Vital Product Data(简称VPD)内部获得,并可通过使用SCSI Inquiry Command检索。
可以获取此VPD的linux命令行实用程序是sdparm
> yum install sdparm
> sdparm --quiet --page=sn /dev/sda
    Unit serial number VPD page:
    3BT1ZQGR000081240XP7

请注意,并非所有设备都有此序列号,市场上充斥着廉价仿冒品,一些USB闪存盘返回奇怪的序列号(例如我的SanDisk Cruzer仅返回字母“u”)。为了克服这个问题,一些人选择通过混合VPD中的不同字符串(如产品ID、供应商ID和序列号)来创建唯一标识符。
C语言代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <scsi/scsi.h>
#include <scsi/sg.h>
#include <sys/ioctl.h>

int scsi_get_serial(int fd, void *buf, size_t buf_len) {
    // we shall retrieve page 0x80 as per http://en.wikipedia.org/wiki/SCSI_Inquiry_Command
    unsigned char inq_cmd[] = {INQUIRY, 1, 0x80, 0, buf_len, 0};
    unsigned char sense[32];
    struct sg_io_hdr io_hdr;
            int result;

    memset(&io_hdr, 0, sizeof (io_hdr));
    io_hdr.interface_id = 'S';
    io_hdr.cmdp = inq_cmd;
    io_hdr.cmd_len = sizeof (inq_cmd);
    io_hdr.dxferp = buf;
    io_hdr.dxfer_len = buf_len;
    io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
    io_hdr.sbp = sense;
    io_hdr.mx_sb_len = sizeof (sense);
    io_hdr.timeout = 5000;

    result = ioctl(fd, SG_IO, &io_hdr);
    if (result < 0)
        return result;

    if ((io_hdr.info & SG_INFO_OK_MASK) != SG_INFO_OK)
        return 1;

    return 0;
}

int main(int argc, char** argv) {
    char *dev = "/dev/sda";
    char scsi_serial[255];
    int rc;
    int fd;

    fd = open(dev, O_RDONLY | O_NONBLOCK);
    if (fd < 0) {
        perror(dev);
    }

    memset(scsi_serial, 0, sizeof (scsi_serial));
    rc = scsi_get_serial(fd, scsi_serial, 255);
    // scsi_serial[3] is the length of the serial number
    // scsi_serial[4] is serial number (raw, NOT null terminated)
    if (rc < 0) {
        printf("FAIL, rc=%d, errno=%d\n", rc, errno);
    } else
    if (rc == 1) {
        printf("FAIL, rc=%d, drive doesn't report serial number\n", rc);
    } else {
        if (!scsi_serial[3]) {
            printf("Failed to retrieve serial for %s\n", dev);
            return -1;
        }
        printf("Serial Number: %.*s\n", (size_t) scsi_serial[3], (char *) & scsi_serial[4]);
    }
    close(fd);

    return (EXIT_SUCCESS);
}

为了完整起见,我也会提供检索ATA设备(hda、hdb等)序列号的代码。这将无法用于USB设备。

#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <linux/hdreg.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <cctype>
#include <unistd.h>

int main(){
    struct hd_driveid *id;
    char *dev = "/dev/hda";
    int fd;

    fd = open(dev, O_RDONLY|O_NONBLOCK);
    if(fd < 0) {
        perror("cannot open");
    }
    if (ioctl(fd, HDIO_GET_IDENTITY, id) < 0) {
        close(fd);
        perror("ioctl error");
    } else {
        // if we want to retrieve only for removable drives use this branching
        if ((id->config & (1 << 7)) || (id->command_set_1 & 4)) {
            close(fd);
            printf("Serial Number: %s\n", id->serial_no);
        } else {
            perror("support not removable");
        }
        close(fd);
    }
}

优秀的描述,我喜欢SCSI和ATA之间的区分。 - Thomas Matthews
做得很好,唯一缺少的是如何确定驱动器是SCSI还是IDE? - chacham15
这很棒,但存在一个错误,仅检查ioctl成功并不足以验证你是否获得了有效的串行通信... 你还需要验证 if ((io_hdr.info & SG_INFO_OK_MASK) != SG_INFO_OK) return -1 - Geoffrey
使用上述修复更新答案。 - Geoffrey

2

这段代码将获取USB序列号...它不像clyfe的那样技术上令人印象深刻,但每次都能解决问题。

#include <unistd.h>
#include <string.h>
#include <stdio.h>

int main(int arg, char **argv) {
    ssize_t len;
    char buf[256], *p;
    char buf2[256];
    int i;

    len = readlink("/sys/block/sdb", buf, 256);
    buf[len] = 0;
    // printf("%s\n", buf);
    sprintf(buf2, "%s/%s", "/sys/block/", buf);
    for (i=0; i<6; i++) {
        p = strrchr(buf2, '/');
        *p = 0;
    }
    // printf("%s\n", buf2);
    strcat(buf2, "/serial");
    // printf("opening %s\n", buf2);

    int f = open(buf2, 0);
    len = read(f, buf, 256);
    if (len <= 0) {
        perror("read()");
    }
    buf[len] = 0;
    printf("serial: %s\n", buf);


}

1

0

最好的方法可能是像命令行工具一样(很可能):从C++代码中检查/proc/sys中的相关文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接