Netlink 接收缓冲区对齐

Netlink receive buffer alignment

静态分析器 PVS-Studio 在 nh = (struct nlmsghdr *) buf

中报告

The pointer 'buf' is cast to a more strictly aligned pointer type.

我认为警告是正确的。这是一个严重的问题吗?这 代码需要在各种架构上可移植。我该如何解决 这个?

我知道一些方法:

还有别的选择吗?

以下代码摘自 netlink manpage.

int len;
char buf[8192];     /* 8192 to avoid message truncation on
                       platforms with page size > 4096 */
struct iovec iov = { buf, sizeof(buf) };
struct sockaddr_nl sa;
struct msghdr msg;
struct nlmsghdr *nh;

msg = { &sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
len = recvmsg(fd, &msg, 0);

for (nh = (struct nlmsghdr *) buf; NLMSG_OK (nh, len);
     nh = NLMSG_NEXT (nh, len)) {
     /* The end of multipart message */
     if (nh->nlmsg_type == NLMSG_DONE)
     return;

     if (nh->nlmsg_type == NLMSG_ERROR)
     /* Do some error handling */
     ...

     /* Continue with parsing payload */
     ...
}

谢谢。

使用分配的 struct nlmsghdr 的指针而不是 char buf[8192] 的指针不是更好吗?

例如:

int len;
struct nlmsghdr buf;
struct iovec iov = { &buf, sizeof(buf) };
struct sockaddr_nl sa;
struct msghdr msg;
struct nlmsghdr *nh;

msg = { &sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
len = recvmsg(fd, &msg, 0);

for (nh = &buf; NLMSG_OK (nh, len);
    nh = NLMSG_NEXT (nh, len)) {
    /* The end of multipart message */
    if (nh->nlmsg_type == NLMSG_DONE)
    return;

    if (nh->nlmsg_type == NLMSG_ERROR)
    /* Do some error handling */
    ...

    /* Continue with parsing payload */
    ...
}