c - 获取接收到的数据包的实际大小

标签 c winsock2

通常在发送任意大小的数据包时,会建立一个最大值并将其用作接收缓冲区的大小。

#include <winsock2.h>

// Socket Description
// Hint.ai_family = AF_INET;
// Hint.ai_socktype = SOCK_DGRAM;
// Hint.ai_protocol = IPPROTO_UDP;

void Send(int Size)
{
    char *Data = (char *)malloc(Size);
    sendto(Socket, Data, Size, NULL, Result->ai_addr, Result->ai_addrlen)
}

void Receive()
{
    const unsigned int MaxDataSize = 1436;
    char *Data = (char *)malloc(MaxDataSize);
    recvfrom(Socket, Data, MaxDataSize, 0, (SOCKADDR*)&RecvAddr, &RecvAddrSize);
}

在这个伪示例中,无论传递给 Send() 的数据大小如何,我们的 Receive() 函数始终以定义的最大大小获取数据。

如何确定原始发送的数据包大小?

最佳答案

MSDN recvfrom() Documentation

If no error occurs, recvfrom returns the number of bytes received. If the connection has been gracefully closed, the return value is zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.

随后,通过使用 MSG_PEEK 标志:

Peeks at the incoming data. The data is copied into the buffer but is not removed from the input queue. The function subsequently returns the amount of data that can be read in a single call to the recvfrom (or recv) function, which may not be the same as the total amount of data queued on the socket. The amount of data that can actually be read in a single call to the recvfrom (or recv) function is limited to the data size written in the send or sendto function call.

这使您可以灵活地读取多个突发中的传入数据包。允许您在发送数据包之前将大小值附加到数据包的开头。然而,这似乎并不像听起来那么微不足道。

我质疑采用这条路线而不是直接分配足够的内存来容纳您将发送的最大数据包是否会带来任何性能提升。

关于c - 获取接收到的数据包的实际大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38323099/

相关文章:

c - 使用套接字在 C 中发送发布数据时出错

c++ - 如何修复递归 Flood Fill 段错误?

Windows RIO socket Registered I/O 发送延迟 RIOSend

c++ - WSARecv 一次可以接收的最大字节数是多少?

c++ - 接收所有使用 C 套接字发送的数据

c++ - 在 winsock 中用 C++ 创建一个套接字并连接到谷歌,并在响应结束时得到一些垃圾

c - 为什么这个程序会导致无限循环输出?

c - 将内核添加到 Windows 启动菜单

c - M 次执行后在 C 中完成多线程程序?

c - 无加速结果的高斯消去法