linux下使用libusb 进行获取设备描述符c代码
时间: 2024-09-30 22:10:13 浏览: 37
Linux下获取USB设备的序列号获取IDE设备的序号C源码
在Linux环境下使用libusb进行设备描述符的获取,首先需要包含必要的库头文件并初始化libusb环境。以下是一个简单的C语言示例代码片段,展示了如何连接到USB设备并读取其描述符:
```c
#include <stdio.h>
#include <libusb.h>
int main(int argc, char* argv[]) {
// 初始化libusb库
int result = libusb_init(NULL);
if (result != LIBUSB_SUCCESS) {
fprintf(stderr, "Failed to initialize libusb: %s\n",
libusb_error_name(result));
return 1;
}
// 找到USB设备
struct libusb_device* device;
result = libusb_get_device_list(NULL, &device_list);
if (result != LIBUSB_SUCCESS) {
fprintf(stderr, "Failed to get devices: %s\n",
libusb_error_name(result));
goto exit_with_cleanup;
}
// 遍历找到的设备
for (struct libusb_device *d = device_list; d != NULL; d = d->next) {
// 检查设备是否为我们需要的
const char* vendor_id = libusb_get_device_string(d, USB_DESC_ID_VENDOR);
const char* product_id = libusb_get_device_string(d, USB_DESC_ID_PRODUCT);
// 如果设备ID匹配,尝试打开设备
if (strcmp(vendor_id, VENDOR_ID) == 0 && strcmp(product_id, PRODUCT_ID) == 0) {
result = libusb_open(d, &device_handle);
if (result == LIBUSB_SUCCESS) {
break;
} else {
fprintf(stderr, "Failed to open device: %s\n",
libusb_error_name(result));
}
}
}
// 如果设备打开成功,获取描述符
if (result == LIBUSB_SUCCESS) {
libusb_device_descriptor desc;
memset(&desc, 0, sizeof(desc));
result = libusb_get_device_descriptor(device_handle, &desc);
if (result == LIBUSB_SUCCESS) {
printf("Device Descriptor:\n");
printf("\tClass: %x\n", desc.bDeviceClass);
// ... 打印其他描述符信息
} else {
fprintf(stderr, "Failed to get device descriptor: %s\n",
libusb_error_name(result));
}
}
exit_with_cleanup:
// 清理并关闭资源
libusb_free_device_list(device_list, 1);
if (device_handle != NULL) {
libusb_close(device_handle);
}
libusb_exit(NULL);
return result == LIBUSB_SUCCESS ? 0 : 1;
}
```
在这个例子中,你需要替换 `VENDOR_ID` 和 `PRODUCT_ID` 为实际的USB设备厂商ID和产品ID。记得在运行前安装libusb开发库 (`sudo apt-1.0-0-dev`)。
阅读全文