xinthose xinthose - 1 year ago 213
Linux Question

Get device path based on USB VID:PID in Linux

If I plug in a device, say

and I want to get the number
based on its VID:PID (found with
), how could I do that in C++ Linux? I have this code to find one printer device, if it's helpful at all:

int printer_open (void)
char printer_location[] = "/dev/usb/lpX";
struct stat buf;

// continuously try all numbers until stat returns true for the connected printer
for (int i = 0; i < 10; i++)
printer_location[11] = '0' + i;
if (!stat (printer_location, &buf))

return 0;

Answer Source

You could use libusb
apt-get install build-essential libudev-dev
Here is a good example:
and here is the lib description:

int main() {
libusb_context *context = NULL;
libusb_device **list = NULL;
int rc = 0;
ssize_t count = 0;

rc = libusb_init(&context);
assert(rc == 0);

count = libusb_get_device_list(context, &list);
assert(count > 0);

for (size_t idx = 0; idx < count; ++idx) {
    libusb_device *device = list[idx];
    libusb_device_descriptor desc = {0};

    rc = libusb_get_device_descriptor(device, &desc);
    assert(rc == 0);

    printf("Vendor:Device = %04x:%04x\n", desc.idVendor, desc.idProduct);

And if you compile your code don't forget to add the lib reference -I/usr/include/libusb-1.0/ and - lusb-1.0

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download