C++ DGRAM socket get the RECEIVER address

后端 未结 2 439
走了就别回头了
走了就别回头了 2020-12-07 03:28

In C++,
how can I get the receiver address of the UDP packet which I have received using recvfrom. I know that it should be the same host on which I

相关标签:
2条回答
  • 2020-12-07 04:22

    I've constructed an example that extracts the source, destination and interface addresses. For brevity, no error checking is provided. See this duplicate: Get destination address of a received UDP packet.

    // 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
    }
    
    0 讨论(0)
  • 2020-12-07 04:24

    On Linux you want to use IP_PKTINFO option, see ip(7), and the recvmsg(2) call.

    Stevens has examples of doing this but with IP_RECVDSTADDR and IP_RECVIF options that are not available on Linux.

    0 讨论(0)
提交回复
热议问题