Init with small code example

This commit is contained in:
2020-05-08 23:12:04 +02:00
commit 171d42863b
4 changed files with 209 additions and 0 deletions

8
kernel/Makefile Normal file
View File

@@ -0,0 +1,8 @@
obj-m += netlink-test.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

81
kernel/netlink-test.c Normal file
View File

@@ -0,0 +1,81 @@
#include <linux/kernel.h>
#include <linux/module.h>
#include <net/sock.h>
#include <net/netlink.h>
#define NETLINK_TESTPROTO (30)
static struct sock *my_nl_sock;
static void nl_test_recv(struct sk_buff *skb)
{
struct nlmsghdr *nlh;
int pid;
struct sk_buff *skb_out;
int msg_size;
char *msg="Hello from kernel";
int res;
printk(KERN_INFO "Entering: %s\n", __FUNCTION__);
msg_size=strlen(msg);
nlh=(struct nlmsghdr*)skb->data;
printk(KERN_INFO "Netlink received msg payload:%s\n",(char*)nlmsg_data(nlh));
pid = nlh->nlmsg_pid; /*pid of sending process */
skb_out = nlmsg_new(msg_size,0);
if(!skb_out)
{
printk(KERN_ERR "Failed to allocate new skb\n");
return;
}
nlh=nlmsg_put(skb_out,0,0,NLMSG_DONE,msg_size,0);
NETLINK_CB(skb_out).dst_group = 0; /* not in mcast group */
strncpy(nlmsg_data(nlh),msg,msg_size);
res=nlmsg_unicast(my_nl_sock,skb_out,pid);
if(res<0)
printk(KERN_INFO "Error while sending bak to user\n");
}
static struct netlink_kernel_cfg nl_cfg = {
.groups = 0,
.input = nl_test_recv,
};
static int nl_test_init(void)
{
my_nl_sock = netlink_kernel_create(&init_net, NETLINK_TESTPROTO, &nl_cfg);
if (!my_nl_sock) {
printk(KERN_ERR "%s: receive handler registration failed\n", __func__);
return -ENOMEM;
}
printk(KERN_INFO "Hello :)\n");
return 0;
}
static void nl_test_exit(void)
{
if (my_nl_sock)
netlink_kernel_release(my_nl_sock);
printk(KERN_INFO "Goodbye :(\n");
}
module_init(nl_test_init);
module_exit(nl_test_exit);
MODULE_AUTHOR("Mario Huettel <mario.huettel@gmx.net>");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Netlink communication test");