简体   繁体   English

C-从UDP套接字缓冲区读取字节(Linux)

[英]C - Read bytes from the UDP socket buffer (Linux)

I wrote the code in order to handle receiving UDP packets. 我编写了代码以处理接收UDP数据包。 The packets are all same length(120 bytes), and about 1,000 packets are coming in every second. 数据包都是相同的长度(120字节),每秒大约有1,000个数据包进入。 Simply, my code is like this. 简而言之,我的代码就是这样。

int sock = -1;
int flag = 0;
int nRead = 0;

#define LOCAL_BUFF_SIZE (8192)
char buff[LOCAL_BUFF_SIZE];

struct sockaddr_in sockAddr;

memset((void *)&sockAddr, 0x00, sizeof(struct sockaddr_in));

if((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
{
    /* Print error and terminate */
}

/* Make it non-blocking */  
flag = fcntl( sock, F_GETFL, 0 );
fcntl( sock, F_SETFL, flag | O_NONBLOCK );

sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(portNum);
sockAddr.sin_addr.s_addr = INADDR_ANY;

if(bind(sock, (struct sockaddr *)&sockAddr, sizeof (sockAddr)) < 0)
{
    /* Print error and terminate */
}

while(...)
{
    nRead = recv(sock, buff, LOCAL_BUFF_SIZE, 0);
    if(nBytes > 0)
    {
        /* Process the data */
    }
    else
    {
        /* If it's error, handle error */
    }
}

When I wrote this code, I expect that recv() function returns every bytes in the UDP socket buffer at that moment, but, it seems that it only returns one packet(120 byte) every time even though there are more bytes in the buffer. 当我编写此代码时,我希望那个时候recv()函数返回UDP套接字缓冲区中的每个字节,但是,即使缓冲区中有更多字节,它似乎每次也仅返回一个数据包(120字节)。 。 So now I encountered with packet loss. 所以现在我遇到了丢包的情况。 I know that there are many other ways to solve this problem, but, for now reading all existent bytes in the UDP buffer at once is the easiest way for me. 我知道还有很多其他方法可以解决此问题,但是,对于我而言,现在一次读取UDP缓冲区中所有存在的字节是最简单的方法。 So, is there any way to read all bytes in the UDP buffer at once? 那么,有没有办法一次读取UDP缓冲区中的所有字节?

Thanks in advance 提前致谢

UDP is a message oriented protocol, therefore, you are getting single message in one recv operation. UDP是一种面向消息的协议,因此,您可以通过一个recv操作获得单个消息。 You can possible use recvmmsg() system call to receive multiple messages in a single call. 您可以使用recvmmsg()系统调用在一个调用中接收多个消息。

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

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