nl.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <errno.h>
  6. #include <asm/types.h>
  7. #include <sys/types.h>
  8. #include <sys/socket.h>
  9. #include <linux/netlink.h>
  10. #include <poll.h>
  11. #include "nl.h"
  12. int nl_init(void)
  13. {
  14. struct sockaddr_nl nl_addr;
  15. int nl;
  16. memset(&nl_addr, 0, sizeof(nl_addr));
  17. nl_addr.nl_family = AF_NETLINK;
  18. nl_addr.nl_pad = 0;
  19. nl_addr.nl_pid = 0; /* Let kernel to assign id */
  20. nl_addr.nl_groups = -1; /* Listen all multicast */
  21. if ((nl = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT)) < 0) {
  22. fprintf(stderr, "Error: Can't create socket\n");
  23. return -1;
  24. }
  25. if (bind(nl, (void *)&nl_addr, sizeof(nl_addr))) {
  26. fprintf(stderr, "Error: Can't bind NetLink\n");
  27. return -1;
  28. }
  29. return nl;
  30. }
  31. void nl_close(int nl)
  32. {
  33. if (nl >= 0)
  34. close(nl);
  35. }
  36. int nl_poll(int nl, int timeout)
  37. {
  38. struct pollfd pfd;
  39. char buf[10];
  40. int n;
  41. pfd.events = POLLIN;
  42. pfd.fd = nl;
  43. n = poll(&pfd, 1, (timeout * 1000));
  44. if (n < 0) {
  45. if (EINTR == errno)
  46. return -2;
  47. return -1;
  48. }
  49. /* Some device-related event */
  50. /* Read all messages. We don't need a message content. */
  51. if (n > 0)
  52. while (recv(nl, buf, sizeof(buf), MSG_DONTWAIT) > 0);
  53. return n;
  54. }