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

收到UDP数据包后,我需要用他用来向其发送数据包的地址来响应发送方。

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


烙印99
浏览 436回答 3
3回答

BIG阳

我构建了一个示例,该示例提取了源地址,目标地址和接口地址。为简便起见,没有提供错误检查。// sock is bound AF_INET socket, usually SOCK_DGRAM// include struct in_pktinfo in the message "ancilliary" control datasetsockopt(sock, IPPROTO_IP, IP_PKTINFO, &opt, sizeof(opt));// the control data is dumped herechar cmbuf[0x100];// the remote/source sockaddr is put herestruct sockaddr_in peeraddr;// if you want access to the data you need to init the msg_iovec fieldsstruct 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}

守着一只汪

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