为了账号安全,请及时绑定邮箱和手机立即绑定

获取接收到的UDP报文的目的地址

获取接收到的UDP报文的目的地址

拉丁的传说 2019-10-30 10:20:59
收到UDP数据包后,我需要用他用来向其发送数据包的地址来响应发送方。该recvfrom调用使我可以获取发送方的地址,但是如何获取接收到的数据包的目标地址,该地址应与本地主机接口之一的地址匹配?
查看完整描述

3 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

我构建了一个示例,该示例提取了源地址,目标地址和接口地址。为简便起见,没有提供错误检查。


// 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

}


查看完整回答
反对 回复 2019-10-30
?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

为了提供O(1)查找,您需要将辅助控制结构打包到提供O(1)查找的数据容器中。填充该结构的数量至少为辅助控制消息的O(n)。您不必担心要查找的控制消息的复杂性:总是只有少数几个,并且只有您请求的那些。代您还需要零内存管理。这是微不足道的开销。 

查看完整回答
反对 回复 2019-10-30
  • 3 回答
  • 0 关注
  • 914 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信