关于C#:如何使用recvfrom监听来自某个主机的UDP数据报?

How to listen for UDP datagrams from a certain host using recvfrom?

我有一个 C 代码片段,它在 UDP 套接字上侦听传入消息(并且工作正常):

1
2
3
4
5
6
7
8
9
10
11
uint32_t udp_port = 101010; // example port
int sock_udp = socket(AF_INET, SOCK_DGRAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(udp_port);
bind(sock_udp, (struct sockaddr*) &server_address, (socklen_t) sizeof(server_address));

char buffer[20];
struct sockaddr_in sender_address;
socklen_t sender_len = (socklen_t) sizeof(struct sockaddr_in);
ssize_t rcv_len = recvfrom(sock_udp, buffer, sizeof(buffer), 0, (struct sockaddr * ) &sender_address, &sender_len);

之后,我在 sender_address 结构中获得了有关发件人的信息,我可以检查地址、端口等。我的问题是:我可以使用 recvrecvfrom 或其他类似函数来侦听来自某个主机的数据报吗?换句话说,是否有可能在不读取其他来源的情况下丢弃数据报?


如果您connect(2) 数据报套接字,您可以"过滤"并从指定的单一来源接收数据报。

If the socket sockfd is of type SOCK_DGRAM then addr is the address to
which datagrams are sent by default, and the only address from which
datagrams are received.

标准用语有点不同:

For SOCK_DGRAM sockets, the peer address identifies where all
datagrams are sent on subsequent send() functions, and limits the
remote sender for subsequent recv() functions