收到 UDP 数据包后,我需要用他用来发送我要回复的数据包的地址来回复发件人。
该recvfrom
调用让我获得了发送者的地址,但我如何获得接收到的数据包的目标地址,该地址应该与本地主机接口之一的地址匹配?
收到 UDP 数据包后,我需要用他用来发送我要回复的数据包的地址来回复发件人。
该recvfrom
调用让我获得了发送者的地址,但我如何获得接收到的数据包的目标地址,该地址应该与本地主机接口之一的地址匹配?
我构建了一个提取源、目标和接口地址的示例。为简洁起见,不提供错误检查。
// 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
}
您使用 setsockopt 设置 IP_PKTINFO 选项,然后使用 recvmsg 并在 struct msghdr 的 msg_control 成员中获取 in_pktinfo 结构。in_pktinfo 有一个包含数据包目标地址的字段。
请参阅:http ://www.linuxquestions.org/questions/programming-9/how-to-get-destination-address-of-udp-packet-600103/在那里我找到了更多详细信息的答案。