Add Makefile and netlink_logger module for custom netlink messaging

This commit is contained in:
lumos 2025-06-07 23:26:20 +08:00
commit 946a622209
2 changed files with 70 additions and 0 deletions

16
Makefile Normal file
View File

@ -0,0 +1,16 @@
obj-m += netlink_logger.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
load:
sudo insmod netlink_logger.ko
unload:
sudo rmmod netlink_logger

54
netlink_logger.c Normal file
View File

@ -0,0 +1,54 @@
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/netlink.h>
#include <net/sock.h>
#include <linux/skbuff.h>
#define NETLINK_USER_CUSTOM 31
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Leo");
MODULE_DESCRIPTION("Netlink message logger for custom protocol");
static struct sock *nl_sk = NULL;
static void netlink_recv_msg(struct sk_buff *skb)
{
struct nlmsghdr *nlh;
char *payload;
if (!skb)
return;
nlh = nlmsg_hdr(skb);
payload = (char *)nlmsg_data(nlh);
pr_info("[netlink_logger] Received netlink msg: %s\n", payload);
}
static int __init netlink_logger_init(void)
{
struct netlink_kernel_cfg cfg = {
.input = netlink_recv_msg,
};
nl_sk = netlink_kernel_create(&init_net, NETLINK_USER_CUSTOM, &cfg);
if (!nl_sk) {
pr_err("[netlink_logger] Failed to create netlink socket\n");
return -ENOMEM;
}
pr_info("[netlink_logger] Netlink logger module loaded (protocol: %d)\n", NETLINK_USER_CUSTOM);
return 0;
}
static void __exit netlink_logger_exit(void)
{
if (nl_sk)
netlink_kernel_release(nl_sk);
pr_info("[netlink_logger] Module unloaded\n");
}
module_init(netlink_logger_init);
module_exit(netlink_logger_exit);