简体   繁体   English

设置 IP_PKTINFO 时,recvmsg 返回意外的 in_pktinfo

[英]When IP_PKTINFO is set, recvmsg returns an unexpected in_pktinfo

I am writing a program that uses UDP multicast.我正在编写一个使用 UDP 多播的程序。 I need to filter out messages from the specified interface.我需要过滤掉来自指定接口的消息。 I set IP_PKTINFO to socket:我将 IP_PKTINFO 设置为套接字:

int enable = 1;
OS_Result rc = setsockopt(readArg->conn->sock, IPPROTO_IP, IP_PKTINFO, &enable, sizeof(enable));

Then, I print out the contents of in_pktinfo:然后,我打印出 in_pktinfo 的内容:

for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msgHdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&msgHdr, cmsg)) {
    // ignore the control headers that don't match what we want
    if (cmsg->cmsg_level != IPPROTO_IP || cmsg->cmsg_type != IP_PKTINFO) {
        continue;
    }
    struct in_pktinfo *pi = (struct in_pktinfo *)CMSG_DATA(cmsg);
    char interName[20];
    memset(interName, 0, 20);
    if_indextoname(pi->ipi_ifindex, interName);
    printf("! ================================================= !\n");
    printf("ipi_ifindex: %d\n", pi->ipi_ifindex);
    printf("interface name: %s\n", interName);
    printf("ipi_addr: %s\n", inet_ntoa(pi->ipi_addr));
    printf("ipi_spec_dst: %s\n", inet_ntoa(pi->ipi_spec_dst));
    printf("! ================================================= !\n");
}

Unexpected ipi_ifindex and ipi_spec_dst will appear after executing the program multiple times:多次执行程序后会出现意想不到的ipi_ifindex和ipi_spec_dst:

! ================================================= !
ipi_ifindex: 0                                           <------ exception
interface name: 
ipi_addr: 239.255.0.1
ipi_spec_dst: 0.0.0.0
! ================================================= !
! ================================================= !
ipi_ifindex: 2
interface name: ens3
ipi_addr: 239.255.0.1
ipi_spec_dst: 192.168.122.50
! ================================================= !
! ================================================= !
ipi_ifindex: 2
interface name: ens3
ipi_addr: 239.255.0.1
ipi_spec_dst: 192.168.122.50
! ================================================= !

It seems that Linux does not correctly parse out which interface the UDP message is received from.似乎 Linux 没有正确解析出从哪个接口接收到 UDP 消息。 This phenomenon occurs in the first few packets received by socket and the probability appears这种现象发生在socket接收到的前几个包中,概率出现

I have solved this problem.我已经解决了这个问题。 Once the socket is bound to the IP address and port, it begins to receive packets.一旦套接字绑定到 IP 地址和端口,它就开始接收数据包。 So the property of UDP Socket should be set before calling the bind() function.所以 UDP Socket 的属性应该调用bind() function 之前设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM