In this lesson, you will learn how Netlink sockets provide a high-performance, bidirectional communication channel between user-space applications and kernel modules, bypassing the limitations of traditional file-based interfaces.
Beyond File-based Interaction
Previously, we explored procfs and sysfs for runtime configuration. While these are excellent for simple state reading or toggling parameters, they are synchronous and file-bound. When your kernel module needs to push data to user space asynchronously—or handle high-frequency event notification—those interfaces become bottlenecks.
Enter Netlink. Netlink is a socket-based IPC (Inter-Process Communication) mechanism specifically designed for the kernel-to-user-space relationship. Unlike the restrictive file operations of read() or write(), Netlink uses a datagram-oriented message format that allows the kernel to "push" events to user space without waiting for a request, and allows user applications to send structured, typed messages to drivers.
The Workflow
Netlink operates on families (e.g., NETLINK_GENERIC). To use it, a kernel module creates a socket and registers a listener. User space creates a standard socket, binds to the appropriate family, and begins sending/receiving messages encapsulated in nlmsghdr structures.
A simple user-space request to a module might look like this:
int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
struct sockaddr_nl src_addr = { .nl_family = AF_NETLINK, .nl_pid = getpid() };
bind(fd, (struct sockaddr*)&src_addr, sizeof(src_addr));
// Sending a message to the kernel module
send(fd, &my_nl_msg, my_nl_msg.nlmsg_len, 0);
When the kernel receives this, it parses the message payload to trigger specific logic within your module. Conversely, the kernel can use netlink_unicast() or netlink_broadcast() to send messages back to specific user-space processes.
Why this matters
By using Netlink, your modules maintain a clean, message-driven interface. This is the same underlying mechanism used by iproute2 to talk to the kernel networking stack. It is robust, supports security credentials, and handles the asynchronous nature of kernel events far better than polling a file descriptor in /proc.
Key Takeaway: Netlink acts as a high-speed, asynchronous message bus that allows user-space applications to send commands to kernel modules and receive event notifications without the overhead of file-system-based polling.