1 #pragma once
2 
3 #include <linux/rtnetlink.h>
4 
5 template<class Request>
addRouterAttribute(Request & r,int type,const void * data,size_t size)6 inline void addRouterAttribute(Request& r,
7                                int type,
8                                const void* data,
9                                size_t size) {
10     // Calculate the offset into the character buffer where the RTA data lives
11     // We use offsetof on the buffer to get it. This avoids undefined behavior
12     // by casting the buffer (which is safe because it's char) instead of the
13     // Request struct.(which is undefined because of aliasing)
14     size_t offset = NLMSG_ALIGN(r.hdr.nlmsg_len) - offsetof(Request, buf);
15     auto attr = reinterpret_cast<struct rtattr*>(r.buf + offset);
16     attr->rta_type = type;
17     attr->rta_len = RTA_LENGTH(size);
18     memcpy(RTA_DATA(attr), data, size);
19 
20     // Update the message length to include the router attribute.
21     r.hdr.nlmsg_len = NLMSG_ALIGN(r.hdr.nlmsg_len) + RTA_ALIGN(attr->rta_len);
22 }
23