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 结构中获得了有关发件人的信息,我可以检查地址、端口等。我的问题是:我可以使用
如果您
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 subsequentsend() functions, and limits the
remote sender for subsequentrecv() functions