简体   繁体   English

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

[英]Get destination address of a received UDP packet

Upon receiving a UDP packet, I need to respond to the sender with the address he used to send the packet to which I'm replying. 在收到UDP数据包后,我需要使用他用来发送我正在回复的数据包的地址来响应发送方。

The recvfrom call lets me get the address of the sender, but how do I get the destination address of the received packet, which should match the address of one of the local host's interfaces? recvfrom调用让我获取发送方的地址,但是如何获取接收到的数据包的目标地址,该地址应该与本地主机接口之一的地址相匹配?

I've constructed an example that extracts the source, destination and interface addresses. 我构建了一个提取源,目标和接口地址的示例。 For brevity, no error checking is provided. 为简洁起见,未提供错误检查。

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

You set the IP_PKTINFO option using setsockopt and then use recvmsg and get a in_pktinfo structure in the msg_control member of struct msghdr. 使用setsockopt设置IP_PKTINFO选项,然后使用recvmsg并在struct msghdr的msg_control成员中获取in_pktinfo结构。 the in_pktinfo has a field with the destination address of the packet. in_pktinfo有一个包含目标地址的字段。

See: http://www.linuxquestions.org/questions/programming-9/how-to-get-destination-address-of-udp-packet-600103/ where I found the answer for more details. 请参阅: http//www.linuxquestions.org/questions/programming-9/how-to-get-destination-address-of-udp-packet-600103/我在哪里找到了答案以获取更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM