gpt4 book ai didi

linux - 获取收到的UDP数据包的目的地址

转载 作者:行者123 更新时间:2023-11-30 16:06:46 26 4
gpt4 key购买 nike

收到 UDP 数据包后,我需要使用发送者用于发送我要回复的数据包的地址来响应发送者。

recvfrom 调用让我可以获取发送者的地址,但是如何获取接收到的数据包的目标地址,该地址应与本地主机接口(interface)之一的地址相匹配?

最佳答案

我构建了一个提取源地址、目标地址和接口(interface)地址的示例。为了简洁起见,没有提供错误检查。

// sock is bound AF_INET socket, usually SOCK_DGRAM
// include struct in_pktinfo in the message "ancilliary" control data
setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &opt, sizeof(opt));
// the control data is dumped here
char cmbuf[0x100];
// the remote/source sockaddr is put here
struct sockaddr_in peeraddr;
// if you want access to the data you need to init the msg_iovec fields
struct msghdr mh = {
.msg_name = &peeraddr,
.msg_namelen = sizeof(peeraddr),
.msg_control = cmbuf,
.msg_controllen = sizeof(cmbuf),
};
recvmsg(sock, &mh, 0);
for ( // iterate through all the control headers
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&mh);
cmsg != NULL;
cmsg = CMSG_NXTHDR(&mh, 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 = CMSG_DATA(cmsg);
// at this point, peeraddr is the source sockaddr
// pi->ipi_spec_dst is the destination in_addr
// pi->ipi_addr is the receiving interface in_addr
}

关于linux - 获取收到的UDP数据包的目的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59853225/

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