問題描述
在 C++ 中,
如何獲取使用 recvfrom 收到的 UDP 數據包的接收方地址.我知道它應該是我接收數據包的同一臺主機,但我需要從接收到的數據包中提取它,以驗證某些內容.我該怎么做?
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);`
但我收到錯誤:
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.但是,我認為錯誤是更根本的錯誤,而不是包含正確的標題.
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.
請幫忙.
推薦答案
在 Linux 上你想使用 IP_PKTINFO
選項,見 ip(7)
和 recvmsg(2)
調用.
On Linux you want to use IP_PKTINFO
option, see ip(7)
, and the recvmsg(2)
call.
Stevens 有這樣做的例子,但使用 IP_RECVDSTADDR
和 IP_RECVIF
選項在 Linux 上不可用.
Stevens has examples of doing this but with IP_RECVDSTADDR
and IP_RECVIF
options that are not available on Linux.
這篇關于C++ DGRAM 套接字獲取 RECEIVER 地址的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!