3

在 C++ 中,
如何获取使用 recvfrom 接收到的 UDP 数据包的接收方地址。我知道它应该是我接收数据包的同一主机,但我需要从收到的数据包中提取它,以验证某些内容。我怎样才能做到这一点?

我发现这样做的一种方法是:

int r = getsockopt(receiver_sock, SOL_IP, SO_ORIGINAL_DST, (struct sockaddr *) &sender_addr, (socklen_t *)&addr_len);`

但我得到了错误:

error: ‘SO_ORIGINAL_DST’ was not declared in this scope

我正在使用适当的标题

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include </usr/src/linux-headers-2.6.32-21/include/linux/netfilter_ipv4.h>
#include <arpa/inet.h>    
#include <linux/netfilter.h>

使用 netfilter_ipv4 会产生其他错误,例如未声明 INT_MIN。但是,我认为错误是更根本的问题,而不是包含正确的标题。

请帮忙。

4

2 回答 2

3

在 Linux 上,您要使用IP_PKTINFO选项,请参阅ip(7)recvmsg(2)调用。

史蒂文斯有这样做的例子,但有Linux 上不可用的IP_RECVDSTADDR和选项。IP_RECVIF

于 2010-10-15T13:30:53.070 回答
2

我构建了一个提取源、目标和接口地址的示例。为简洁起见,不提供错误检查。请参阅此副本:获取接收到的 UDP 数据包的目标地址

// 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
}
于 2011-03-15T08:32:15.253 回答