netlink.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "netlink.h"
  2. #include <errno.h>
  3. #include <netlink/genl/ctrl.h>
  4. #include <netlink/genl/genl.h>
  5. #include <netlink/handlers.h>
  6. #include <netlink/netlink.h>
  7. #include <netlink/socket.h>
  8. #include "log.h"
  9. int finish_handler(struct nl_msg *msg, void *arg) {
  10. int *ret = arg;
  11. *ret = 0;
  12. return NL_OK;
  13. }
  14. int initNl80211(Netlink* nl, Wifi* w, nl_callback *callback) {
  15. nl->socket = nl_socket_alloc();
  16. if (!nl->socket) {
  17. log_err("NETLINK", "Failed to allocate netlink socket.\n");
  18. return -ENOMEM;
  19. }
  20. nl_socket_set_buffer_size(nl->socket, 0, 0);
  21. if (genl_connect(nl->socket)) {
  22. log_err("NETLINK", "Failed to connect to netlink socket.\n");
  23. nl_close(nl->socket);
  24. nl_socket_free(nl->socket);
  25. return -ENOLINK;
  26. }
  27. nl->id = genl_ctrl_resolve(nl->socket, "nl80211");
  28. if (nl->id< 0) {
  29. log_err("NETLINK", "Nl80211 interface not found.\n");
  30. nl_close(nl->socket);
  31. nl_socket_free(nl->socket);
  32. return -ENOENT;
  33. }
  34. if (callback != NULL) {
  35. nl->cb1 = nl_cb_alloc(NL_CB_DEFAULT);
  36. if (!nl->cb1) {
  37. log_err("NETLINK", "Failed to allocate netlink callback.\n");
  38. nl_close(nl->socket);
  39. nl_socket_free(nl->socket);
  40. return ENOMEM;
  41. }
  42. nl_cb_set(nl->cb1, NL_CB_VALID , NL_CB_CUSTOM, callback, w);
  43. nl_cb_set(nl->cb1, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &(nl->result));
  44. }
  45. return nl->id;
  46. }