首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取接收到的UDP数据包的目的地址

获取接收到的UDP数据包的目的地址
EN

Stack Overflow用户
提问于 2011-03-12 16:07:09
回答 2查看 21.3K关注 0票数 25

在接收到UDP数据包时,我需要使用发送者用来发送我要回复的数据包的地址进行响应。

recvfrom调用让我获得发送者的地址,但是我如何获得接收到的包的目的地址,它应该与本地主机的接口之一的地址相匹配?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-03-12 17:29:16

使用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/,其中我找到了答案。

票数 17
EN

Stack Overflow用户

发布于 2011-03-15 16:30:26

我构造了一个提取源地址、目标地址和接口地址的示例。为简洁起见,未提供错误检查。

代码语言:javascript
复制
// 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
}
票数 24
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5281409

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档