【问题标题】:Incorrect len of msg in netlink socketnetlink 套接字中 msg 的 len 不正确
【发布时间】:2025-12-01 16:20:03
【问题描述】:
【问题讨论】:
标签:
sockets
linux-device-driver
netlink
【解决方案1】:
您可能需要查看文档以确保正确使用“NLMSG_SPACE”、“NLMSG_PAYLOAD”和“NLMSG_DATA”等宏。
额外数据可能来自数据帧的未使用部分,并且您的程序未正确读取消息长度。 (实际上,没有正确使用宏。)例如,如果您发送 1 个字节,我相信实际上会发送 4 个字节,因为 NLMSG_SPACE 将四舍五入为 4 的倍数以“对齐”数据包。
不过读取应该没问题,只需使用宏来获取数据的真实长度,然后只读取这么多。
这是一个获取缓冲区指针和缓冲区长度的示例。
// Get a pointer to the start of the data in the buffer and the buffer (payload) length
buf = (u_char *) (NLMSG_DATA(nlh));
len = NLMSG_PAYLOAD(nlh, 0);
Here are the definitions of the macros.如果你想看看那些。 This here is probably more understandable.
您链接到的代码正在发送字符并通过“memset”将数据设置为 0 来摆脱它,因此打印该 char 数组就可以了。
希望这会有所帮助。如果您无法使其正常工作,请发布一些代码。