nex – Linux netlink programming for kernel and user spaces

There are ways to communicate with Linux kernel, including /proc, debugfs, syscall and etc. Most of them are unidirectional, from the kernel to the user space. /proc could be used to ‘write’ to the kernel but mostly in small data transmission. The most flexible and reliable bidirectional communication should be netlink. This post will talk about netlink programming both in the kernel and the user space, using real working examples – nex. K.R.K.C.

1. netlink programming in the user space

This may be the most common way to do netlink programming. ‘man 7 netlink’/’man netlink’ should give the details and the concrete examples. Eventually, from the user space, netlink is a special socket, which means all you need to do is socket() and bind(). As long as there is a target socket address, send()/recv() should work. NOTE: the socket() should like this ‘socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);’. PF_NETLINK is the one for netlink; only UDP/raw works for netlink for the transport type. As the kernel has defined a lot of messages/protocols used to communicate with, the 3rd parameter should be the number standing for that message/protocol, like NETLINK_ROUTE.

2. netlink programming in the user space

If a new message/protocol is needed to talk to the kernel, which means there would be a user-defined message/protocol used by both the kernel and the user-space application, then netlink programming in the kernel space is needed. All the essential thing here is netlink_kernel_create() once the message is determined. Within this kernel function, a callback API used to process the message has to be provided. Once there is a netlink message from the user space, the netlink socket within the kernel space will receive it and process it using the callback API. NOTE: in the latest version of Linux kernel (3.9/3.10), to create a netlink socket in the kernel, your could should look like below:

struct netlink_kernel_cfg cfg = {
.input = hello_nl_recv_msg,
nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);

But the older version (2.6/3.X) may look like this:

nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, 0, hello_nl_recv_msg,

Project Name: nex
Destination: Linux netlink programming examples
Language: C
IDE: Vim
Project Web:
Git Read Only:

About daveti

Interested in kernel hacking, compilers, machine learning and guitars.
This entry was posted in Dave's Tools, OS, Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.