nl.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. nl_fds_t * 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(nl_fds_t *nl_fds)
  32. {
  33. int fd;
  34. int i;
  35. if (!nl_fds)
  36. return;
  37. for (i = 0; i < NL_FDS_LEN; i++) {
  38. if (nl_fds[i] >= 0)
  39. close(nl_fds[i]);
  40. }
  41. }
  42. int nl_poll(nl_fds_t *nl_fds, int timeout)
  43. {
  44. struct pollfd pfd;
  45. char buf[10];
  46. int n;
  47. pfd.events = POLLIN;
  48. pfd.fd = nl;
  49. n = poll(&pfd, 1, (timeout * 1000));
  50. if (n < 0) {
  51. if (EINTR == errno)
  52. return -2;
  53. return -1;
  54. }
  55. /* Some device-related event */
  56. /* Read all messages. We don't need a message content. */
  57. if (n > 0)
  58. while (recv(nl, buf, sizeof(buf), MSG_DONTWAIT) > 0);
  59. return n;
  60. }