[PATCH net-next v2 01/10] netlink: Introduce nlmsg_payload helper

From: Breno Leitao
Date: Mon Apr 14 2025 - 09:25:07 EST


Create a new helper function, nlmsg_payload(), to simplify checking and
retrieving Netlink message payloads.

This reduces boilerplate code for users who need to verify the message
length before accessing its data.

Suggested-by: Jakub Kicinski <kuba@xxxxxxxxxx>
Signed-off-by: Breno Leitao <leitao@xxxxxxxxxx>
Reviewed-by: Jakub Kicinski <kuba@xxxxxxxxxx>
Reviewed-by: Kuniyuki Iwashima <kuniyu@xxxxxxxxxx>
---
include/net/netlink.h | 16 ++++++++++++++++
1 file changed, 16 insertions(+)

diff --git a/include/net/netlink.h b/include/net/netlink.h
index 29e0db9403820..82e07e272290a 100644
--- a/include/net/netlink.h
+++ b/include/net/netlink.h
@@ -611,6 +611,22 @@ static inline int nlmsg_len(const struct nlmsghdr *nlh)
return nlh->nlmsg_len - NLMSG_HDRLEN;
}

+/**
+ * nlmsg_payload - message payload if the data fits in the len
+ * @nlh: netlink message header
+ * @len: struct length
+ *
+ * Returns: The netlink message payload/data if the length is sufficient,
+ * otherwise NULL.
+ */
+static inline void *nlmsg_payload(const struct nlmsghdr *nlh, size_t len)
+{
+ if (nlh->nlmsg_len < nlmsg_msg_size(len))
+ return NULL;
+
+ return nlmsg_data(nlh);
+}
+
/**
* nlmsg_attrdata - head of attributes data
* @nlh: netlink message header

--
2.47.1