C++ DGRAM 套接字获取 RECEIVER 地址

2023-01-20C/C++开发问题
5

本文介绍了C++ DGRAM 套接字获取 RECEIVER 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 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_RECVDSTADDRIP_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 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6