如何在C中读取可变长度的UDP数据包 [英] How to read UDP packet with variable length in C
问题描述
我正在通过 UDP 发送一个 C 结构
I'm sending a C struct over UDP
struct packet{
int numInt;
int* intList; //malloc'ed as (sizeof(int)*numInt)
}
它将被序列化为[numInt][intList[0]]...[intList[numInt-1]]
.
我的理解是在 UDP 上调用 recvfrom
将读取整个数据包,即使缓冲区没有保存那么多字节.使用非常大的缓冲区是我唯一的选择吗?
My understanding is that calling recvfrom
on UDP will read the entire packet, even if the buffer doesn't hold that many bytes. Is using a really large buffer the only option I have?
推荐答案
您可以将 MSG_PEEK
传递给 recvfrom
以确定缓冲区需要多大.所以只需 recvfrom
几个字节和 MSG_PEEK
就可以找到 numInt
然后 recvfrom
真正的东西(这次没有 <代码>MSG_PEEK).
You could pass MSG_PEEK
to recvfrom
to find out exactly how big the buffer needs to be. So just recvfrom
a few bytes with MSG_PEEK
to find numInt
and then recvfrom
the real thing (this time without MSG_PEEK
).
标准说明了一些关于MSG_PEEK
,但是 kernel.org 拼写得更好:
The standard says something about MSG_PEEK
, but kernel.org spells it better:
MSG_PEEK
这个标志使接收操作从接收队列的开始而不从队列.因此,后续的接收调用将返回相同的数据.
This flag causes the receive operation to return data from the beginning of the receive queue without removing that data from the queue. Thus, a subsequent receive call will return the same data.
显然,在某些时候您会开始怀疑将系统调用的数量加倍以节省内存是否值得.我认为不是.
Obviously at some point you will start wondering if doubling the number of system calls to save memory is worth it. I think it isn't.
这篇关于如何在C中读取可变长度的UDP数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!