首页 > 解决方案 > Netlink 接收缓冲区对齐

问题描述

PVS-Studio,一个静态分析器,报告说nh = (struct nlmsghdr *) buf

指针“buf”被转换为更严格对齐的指针类型。

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

我知道一些方法:

还有其他选择吗?

下面的代码取自netlink 手册页

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 */
     ...
}

谢谢。

标签: clinuxnetlink

解决方案


用一个已分配的指针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 */
    ...
}

推荐阅读