Skip to content

Instantly share code, notes, and snippets.

@VioletEternity
Last active April 30, 2023 23:28
Show Gist options
  • Save VioletEternity/0c9db56bc5a673e9cda4fcbd59780c6e to your computer and use it in GitHub Desktop.
Save VioletEternity/0c9db56bc5a673e9cda4fcbd59780c6e to your computer and use it in GitHub Desktop.
// cc $(pkg-config --cflags --libs libudev) udev_find_serial_by_vid_pid.c -o udev_find_serial_by_vid_pid
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libudev.h>
int main(int argc, char **argv)
{
if (argc != 3) {
fprintf(stderr, "Usage: %s VID PID\n", argv[0]);
return 1;
}
struct udev *ctx = udev_new();
struct udev_enumerate *enm = udev_enumerate_new(ctx);
udev_enumerate_add_match_subsystem(enm, "tty");
udev_enumerate_add_match_property(enm, "ID_BUS", "usb");
udev_enumerate_scan_devices(enm);
int found = 0;
struct udev_list_entry *devices = udev_enumerate_get_list_entry(enm), *device;
udev_list_entry_foreach(device, devices) {
const char *syspath = udev_list_entry_get_name(device);
struct udev_device *dev = udev_device_new_from_syspath(ctx, syspath);
if (!strcmp(udev_device_get_property_value(dev, "ID_VENDOR_ID"), argv[1]) &&
!strcmp(udev_device_get_property_value(dev, "ID_MODEL_ID"), argv[2])) {
puts(udev_device_get_devnode(dev));
found = 1;
}
udev_device_unref(dev);
}
udev_enumerate_unref(enm);
udev_unref(ctx);
return (found == 1) ? 0 : 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment