2 * netlink-echo: Receives a string from user-space and echoes it back.
3 * It's just yet another netlink usage example.
5 * FIXME: I don't whether it's ok to call netlink_unicast() from
6 * netlink_echo_input().
8 * Luiz Fernando N. Capitulino
9 * <lcapitulino@gmail.com>
11 #include <linux/kernel.h>
12 #include <linux/module.h>
13 #include <linux/init.h>
14 #include <linux/string.h>
15 #include <linux/mutex.h>
16 #include <linux/net.h>
17 #include <linux/skbuff.h>
18 #include <linux/netlink.h>
21 #define NETLINK_ECHO 20 // always check whether this is safe
23 static struct sock
*nl
;
24 static DEFINE_MUTEX(netlink_echo_mutex
);
26 static void send_packet(int pid
, const char *message
)
32 len
= NLMSG_SPACE(strlen(message
) + 1);
33 skb
= alloc_skb(len
, GFP_ATOMIC
);
35 printk(KERN_ERR
"[netlink_echo]: cannot allocate memory\n");
39 nlh
= NLMSG_PUT(skb
, 0, 0, 0, len
- sizeof(*nlh
));
40 strcpy(NLMSG_DATA(nlh
), message
);
42 NETLINK_CB(skb
).pid
= 0; /* from kernel */
43 NETLINK_CB(skb
).dst_group
= 0; /* unicast */
44 netlink_unicast(nl
, skb
, pid
, GFP_ATOMIC
);
52 static void netlink_echo_input(struct sk_buff
*skb
)
57 mutex_lock(&netlink_echo_mutex
);
59 if (skb
->len
< sizeof(*nlh
))
63 msg
= NLMSG_DATA(nlh
);
64 send_packet(nlh
->nlmsg_pid
, msg
);
66 mutex_unlock(&netlink_echo_mutex
);
69 static int __init
netlink_echo_init(void)
71 nl
= netlink_kernel_create(&init_net
, NETLINK_ECHO
, 0,
72 netlink_echo_input
, NULL
, THIS_MODULE
);
74 printk(KERN_ERR
"[netlink_echo]: cannot create socket\n");
81 static void __exit
netlink_echo_exit(void)
83 sock_release(nl
->sk_socket
);
86 module_init(netlink_echo_init
);
87 module_exit(netlink_echo_exit
);
89 MODULE_LICENSE("GPL");
90 MODULE_AUTHOR("Luiz Capitulino <lcapitulino@gmail.com>");
91 MODULE_DESCRIPTION("Netlink example module");