C++ DGRAM套接字获取RECEIVER地址
在 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 未声明。但是,我认为这个错误是更根本的错误,而不是包含正确的标头。
请帮忙。
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 am receiving the packet, but I need to extract it from the received packet, in order to verify something. How can I do this?
I found that one way of doing this is:
int r = getsockopt(receiver_sock, SOL_IP, SO_ORIGINAL_DST, (struct sockaddr *) &sender_addr, (socklen_t *)&addr_len);`
But I get the error:
error: ‘SO_ORIGINAL_DST’ was not declared in this scope
I am using the appropriate headers
#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>
Using netfilter_ipv4 gives other errors like INT_MIN not declared. However, I think the mistake is something more fundamental rather than inclusion of proper header.
Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Linux 上,您想要使用
IP_PKTINFO
选项,请参阅ip(7)
和recvmsg(2)
调用。Stevens 有执行此操作的示例,但使用
IP_RECVDSTADDR
和IP_RECVIF
选项在 Linux 上不可用。On Linux you want to use
IP_PKTINFO
option, seeip(7)
, and therecvmsg(2)
call.Stevens has examples of doing this but with
IP_RECVDSTADDR
andIP_RECVIF
options that are not available on Linux.我构建了一个提取源地址、目标地址和接口地址的示例。为了简洁起见,没有提供错误检查。请参阅此副本:获取收到的 UDP 数据包的目标地址。
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.