netlink.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* https://cirosantilli.com/linux-kernel-module-cheat#netlink-sockets */
  2. #include <linux/delay.h> /* usleep_range */
  3. #include <linux/module.h>
  4. #include <linux/netlink.h>
  5. #include <linux/skbuff.h>
  6. #include <net/sock.h>
  7. #include <lkmc/netlink.h>
  8. struct sock *nl_sk = NULL;
  9. static u32 count;
  10. static u32 sleep;
  11. module_param(sleep, int, S_IRUSR | S_IWUSR);
  12. static void callback(struct sk_buff *skb)
  13. {
  14. char readbuf[9];
  15. size_t readbuflen;
  16. int pid;
  17. int res;
  18. struct nlmsghdr *nlh;
  19. struct sk_buff *skb_out;
  20. nlh = (struct nlmsghdr *)skb->data;
  21. pr_info("kernel received: %s\n", (char *)nlmsg_data(nlh));
  22. if (sleep)
  23. usleep_range(1000000, 1000001);
  24. readbuflen = snprintf(readbuf, sizeof(readbuf), "%x", count);
  25. count++;
  26. pid = nlh->nlmsg_pid;
  27. skb_out = nlmsg_new(readbuflen, 0);
  28. if (!skb_out) {
  29. pr_err("nlmsg_new\n");
  30. return;
  31. }
  32. nlh = nlmsg_put(skb_out, 0, 0, NLMSG_DONE, readbuflen, 0);
  33. NETLINK_CB(skb_out).dst_group = 0;
  34. strncpy(nlmsg_data(nlh), readbuf, readbuflen);
  35. res = nlmsg_unicast(nl_sk, skb_out, pid);
  36. if (res < 0)
  37. pr_info("nlmsg_unicast\n");
  38. }
  39. static int myinit(void)
  40. {
  41. struct netlink_kernel_cfg cfg = {
  42. .input = callback,
  43. };
  44. nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);
  45. if (!nl_sk) {
  46. pr_err("netlink_kernel_create\n");
  47. return -10;
  48. }
  49. return 0;
  50. }
  51. static void myexit(void)
  52. {
  53. netlink_kernel_release(nl_sk);
  54. }
  55. module_init(myinit);
  56. module_exit(myexit);
  57. MODULE_LICENSE("GPL");