gpt4 book ai didi

c - 从 sys/socket.h 了解 msghdr 结构

转载 作者:IT王子 更新时间:2023-10-29 00:51:07 27 4
gpt4 key购买 nike

我试图理解 sys/socket.hmsghdr 结构的以下成员图书馆。

  • struct iovec *msg_iov 分散/聚集数组
  • void *msg_control 辅助数据,见下文

内容如下:

Ancillary data consists of a sequence of pairs, each consisting of a cmsghdr structure followed by a data array. The data array contains the ancillary data message, and the cmsghdr structure contains descriptive information that allows an application to correctly parse the data.


我假设 msghdr 结构包含协议(protocol)头信息?如果是这样... *msg_iov 是请求/响应中参数的输入/输出“vector ”吗? *msg_control 包含响应消息?

最佳答案

msg_iov是长度为 msg_iovlen 的输入/输出缓冲区数组.该数组的每个成员都包含一个指向数据缓冲区的指针和缓冲区的大小。这是要读取/写入的数据所在的位置。它允许您读取/写入不一定位于连续内存区域中的缓冲区数组。

msg_control指向大小为 msg_controllen 的缓冲区包含有关数据包的附加信息。要读取这个字段,首先需要声明一个struct cmsghdr * (我们称之为 cmhdr )。您可以通过调用 CMSG_FIRSTHDR() 来填充它第一次,将 msghdr 的地址传递给它结构,和 CMSG_NXTHDR()随后每次,将 msghdr 的地址传递给它结构和 cmhdr 的当前值.

来自msg_control ,您可以找到一些有趣的信息,例如数据包的目标 IP(对多播有用)和 IP header 中 TOS/DSCP 字节的内容(对自定义拥塞控制协议(protocol)有用)等。在大多数情况下,您需要制作 setsockopt调用以启用接收此数据。在给出的示例中,IP_PKTINFOIP_TOS需要启用选项。

参见 cmsg(3) manpage了解更多详情。

源IP和端口,不在msg_control中, 但在 msg_name它需要一个指向 struct sockaddr 的指针长度msg_namelen .

这是一个如何使用它的例子:

struct msghdr mhdr;
struct iovec iov[1];
struct cmsghdr *cmhdr;
char control[1000];
struct sockaddr_in sin;
char databuf[1500];
unsigned char tos;

mhdr.msg_name = &sin
mhdr.msg_namelen = sizeof(sin);
mhdr.msg_iov = iov;
mhdr.msg_iovlen = 1;
mhdr.msg_control = &control;
mhdr.msg_controllen = sizeof(control);
iov[0].iov_base = databuf;
iov[0].iov_len = sizeof(databuf);
memset(databuf, 0, sizeof(databuf));
if ((*len = recvmsg(sock, &mhdr, 0)) == -1) {
perror("error on recvmsg");
exit(1);
} else {
cmhdr = CMSG_FIRSTHDR(&mhdr);
while (cmhdr) {
if (cmhdr->cmsg_level == IPPROTO_IP && cmhdr->cmsg_type == IP_TOS) {
// read the TOS byte in the IP header
tos = ((unsigned char *)CMSG_DATA(cmhdr))[0];
}
cmhdr = CMSG_NXTHDR(&mhdr, cmhdr);
}
printf("data read: %s, tos byte = %02X\n", databuf, tos);
}

关于c - 从 sys/socket.h 了解 msghdr 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32593697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com