gpt4 book ai didi

c - 如何在C中读取可变长度的UDP数据包

转载 作者:太空狗 更新时间:2023-10-29 16:09:02 27 4
gpt4 key购买 nike

我正在通过 UDP 发送 C 结构

struct packet{
int numInt;
int* intList; //malloc'ed as (sizeof(int)*numInt)
}

它将被序列化为[numInt][intList[0]]...[intList[numInt-1]]

我的理解是,在 UDP 上调用 recvfrom 将读取整个数据包,即使缓冲区没有那么多字节。使用非常大的缓冲区是我唯一的选择吗?

最佳答案

您可以将 MSG_PEEK 传递给 recvfrom 以准确了解缓冲区需要多大。所以只需使用 MSG_PEEK recvfrom 几个字节来找到 numInt 然后 recvfrom 真正的东西(这次没有 MSG_PEEK).

The standard说了一些关于 MSG_PEEK 的事情,但是 kernel.org拼写更好:

MSG_PEEK

This flag causes the receive operation to return data from thebeginning of the receive queue without removing that data from thequeue. Thus, a subsequent receive call will return the same data.

显然,在某些时候您会开始怀疑是否值得将系统调用次数加倍以节省内存。我认为不是。

关于c - 如何在C中读取可变长度的UDP数据包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8003170/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com