Overview

A socket used for “inter-process communication” between kernel processes and user space processes.

Netlink sockets are used to send messages to specific subsystems. Each subsystem will contain its own protocol.

Netlink was originally developed with a fixed number of subsystems it could communicate with. There were a static allocation of subsystem IDs and corresponding protocols. This is referred to as classic netlink.

Later on, Netlink was revised to allow for dynamic registration of new subsystems. This allowed for the creation of new subsystems and protocols. This is referred to as generic netlink.

Netlink sockets are created using the socket function from sys/socket.h

Example Call

socket(AF_NETLINK, socket_type, netlink_family)

The first is the socket domain. It will always be AF_NETLINK.

socket_type

There are two valid values for socket_type:

  1. SOCK_RAW
  2. SOCK_DGRAM

However, the netlink protocol makes no distinctions between the two types. Therefore, the choice is inconsequential.

Indicates the kernel module or netlink group to communicate with.

There are quite a few choices, so here are a few examples:

  • NETLINK_ROUTE
    • Used for sending route and link updates.
    • Modify route tables, IP addresses, queuing, packet classifiers, etc..
  • NETLINK_SOCKET_DIAG
    • Query information regarding various types of sockets
  • NETLINK_FIB_LOOKUP
    • Forwarding Information Base (FIB) lookups
  • NETLINK_NETFILTER
    • Netfilter subsystem

Messages are just a byte stream which consists of one or more nlmsghdr structs and their associated payloads.

Every netlink message is prefixed by a nlmsghdr. Additionally, netlink protocols each have their own associated metadata headers. These specific protocol headers are added after the required nlmsghdr.

nlmsghdr struct

struct nlmsghdr {
	__u32 nlmsg_len;    /* Length of message including header */
	__u16 nlmsg_type;   /* Type of message content */
	__u16 nlmsg_flags;  /* Additional flags */
	__u32 nlmsg_seq;    /* Sequence number */
	__u32 nlmsg_pid;    /* Sender port ID */
};

**When sending multipart messages, every message, except the last, must contain the NLM_F_MULTI flag. The final message must nlmsg_type of NLMSG_DONE **

Each netlink family usually has corresponding definitions for nlmsg_type.

Payload