c++ - 确定系统队列中下一个 UDP 数据报的大小

标签 c++ c windows udp winsock

我想知道系统队列中下一个 UDP 数据报的大小。

我找到了 this question有类似的疑问,但是使用了boost。最后一个答案(截至 2010 年 9 月 23 日)说了一些关于在 OS X 中使用 getsockoptSO_NREAD 选项的内容,但我在 Windows 中找不到任何相关信息(使用 Winsock)。

Here我发现我可以使用 ioctlsocketFIONREAD 来找出整个队列的大小,但我没有找到关于第一个数据报的任何信息。

所以我的问题是: 有没有办法使用套接字 API 确定队列中下一个 UDP 数据报的大小?(我没有使用 boost)。

我希望我的代码看起来像这样:

char BigBuffer[ 64 * 1024 ];
void Read( void *Buf, size_t Size ) {
    size_t LengthInQueue = WhatTheSizeOfTheNextDatagram();
    if( Size < LengthInQueue ) {
         recvfrom( Socket, BigBuffer, 64*1024,  /*...*/ );
         memcpy( Buf, BigBuffer, Size );
    }
    else {
         recvfrom( Socket, Buf, size,  /*...*/ );
    }
}

为了空间和可读性,我省略了错误检查和一些参数。 我想避免在不需要时复制到中间缓冲区。

最佳答案

如果我理解正确的话,你只是想确保 Buf 不会溢出,但你不关心任何超出 Size 的额外数据,因为你无论如何都要丢弃它。在这种情况下,您只需要:

recvfrom( Socket, Buf, size,  /*...*/ );

数据包的剩余部分被自动丢弃。

引自the docs :

For message-oriented sockets, data is extracted from the first enqueued message, up to the size of the buffer specified. If the datagram or message is larger than the buffer specified, the buffer is filled with the first part of the datagram, and recvfrom generates the error WSAEMSGSIZE. For unreliable protocols (for example, UDP) the excess data is lost.

关于c++ - 确定系统队列中下一个 UDP 数据报的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3782182/

相关文章:

windows - "Open With"使用CMD

c++ - 避免 vector 复制构造函数

Linux 上的 C free() 报告无效的下一个大小错误、数组指针、Mac 上的相同代码传递

c - C 中的数组 asm 函数

c - 如何在 C 中分配连续的二维字符串数组

windows - 如何在 Windows 上执行非阻塞 IPC 读取?

c - 如何在 Linux 或 Macos 中为 Windows 编译静态 .lib 库

c++ - Boost 1_52 构建 VS2012 失败

C++ stringstream 转换为 double with operator>>

c++ - 重新启动后,线程无法在while循环中再次运行