简体   繁体   English

是否有任何 C 套接字 function 可以查找来自特定 UDP 客户端的数据报?

[英]Is there any C socket function, which can look for datagrams from a specific UDP client?

The server I am building uses the UDP transport layer protocol.我正在构建的服务器使用 UDP 传输层协议。 I have a scenario where multiple clients can send datagrams to my server.我有一个场景,多个客户端可以将数据报发送到我的服务器。 But each client may send the data across multiple datagrams, and before starting to process the data, I need to have the entire data at the server.但是每个客户端可能会跨多个数据报发送数据,在开始处理数据之前,我需要在服务器上拥有整个数据。 From the man page of recvfrom() , it sounds like it reads the datagrams from any UDP client.recvfrom()的手册页中,听起来它从任何 UDP 客户端读取数据报。 Are there any recv*() family functions that enable us to read from a specific UDP client?是否有任何recv*()系列函数使我们能够从特定的 UDP 客户端读取?

#include <netinet/in.h>
#include <sys/socket.h>

int append_data(void* buf, int size);

int main()
{
    /* Create a UDP socket and bind to a port */
    int sockfd;
    char rd_buf[100];

    struct sockaddr_in cliaddr;

    for ( ; ; ) {
        /* Recvfrom any client */

        int addr_len = sizeof(cliaddr);
        int rd_status = recvfrom(sockfd, rd_buf, sizeof(rd_buf), 0, (struct sockaddr*) &cliaddr, &addr_len);

        if (append_data(rd_buf, rd_status) == DATA_COMPLETE)
            continue;

        /* Recvfrom a particular client */

        for ( ; ; ) {
            /* Any function similar to recvfromcli() ? */

            int rd_status = recvfromcli(sockfd, rd_buf, sizeof(rd_buf), 0, (struct sockaddr*) &cliaddr, addr_len);

            if (append_data(rd_buf, rd_status) == DATA_COMPLETE)
                 break;
        }
    }
}

If not what are my other alternatives?如果不是,我的其他选择是什么?

You can create a separate UDP socket that is bind() 'ed to the local IP/Port and connect() 'ed to a specific client IP/Port, then you can recv() using that socket, and it will give you datagrams from only that client.您可以创建一个单独的 UDP 套接字,该套接字bind()被绑定到本地 IP/端口,并且connect()被绑定到特定客户端 IP/端口,然后您可以使用该套接字进行recv() ,它会给您数据报仅来自该客户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM