Excerpted from Wikipedia:
Netlink socket family is a Linux kernel interface used for inter-process communication (IPC) between both the kernel and userspace processes, and between different userspace processes, in a way similar to the Unix domain sockets. Similarly to the Unix domain sockets, and unlike INET sockets, Netlink communication cannot traverse host boundaries. However, while the Unix domain sockets use the file system namespace, Netlink processes are addressed by process identifiers (PIDs).
From the description above, it is not hard to know that Netlink acts as a bridge between the kernel and userspace program. Netlink protocol is datagram-oriented and has its own communication protocol.
In this post, we will focuse on the NETLINK_ROUTE protocol – a protocol of AF_NETLINK family. All the supported netlink protocols can be found in man(7) netlink.
- Understanding And Programming With Netlink Sockets
- man(7) netlink
- man(3) netlink
- man(7) rtnetlink
- man(3) rtnetlink
- Linux Kernel source code - netlink
Netlink message contains one or more nlmsghdr structures, each of them has a associated payload. The payload is varied according to the netlink meesage type which is indicated by
nlmsg_type field. In this post, we are mainly
NETLINK_ROUTE message type.
As the man(7) netlink suggested, the netlink byte stream should be accessed only with the standard
NLMSG_* macros, man(3) netlink for more details.
To better illustrate the layout of netlink protocol, visual view is the best.
Due to the fact that
staruct nlmsghdr has already well aligned on some architecture (e.g. my x86_64 Linux), so the paddings in the picture above maybe not present in the real world.
rtnetlink, as described in man(3) rtnetlink, allows user to read and modify kernel’s routing table. Each rtnetlink message contains one rtnetlink header, and followed by one or more attributes which is represented by
The header structure of rtnetlink is varied according to different message type.
We will mainly introduce
RTM_GETADDR types in this post to illustrate how to set and get IP address via Netlink protocol.
RTM_GETADDR message types have the same message header structure, i.e.
As dictated before, each rtnetlink message is made up of two parts – one header and one or more optional attributes. The attributes contain the actual values which is passed via netlink. For example, when setting IP address, netlink header indicates that we opt rtnetlink message type to read and modify kernel’s routing table (include IP address assigning), rtnetlink header designates that we are interested in IP manipulation, and the attributes carry the actual IP address value.
Attributes has the structure below:
RTM_GETADDR message type, there 7 available attribute types.
Here we post a simple example to illustrate the usage of netlink. The full code can be found on my Github.
Download this code and compile it with
Share Link: http://d0u9.win/posts/2213062665.html