Sendto- 强制发送 X 字节的 UDP 数据报

Sendto- forcing sending a UDP datagram of X bytes

我有一个关于 sendto 的基本问题:

假设我们希望目的地将接收正好 X 字节的 UDP 数据包。这意味着,它不能接收小于 X 字节的数据包(如果 sendto returns 小于 X 字节是可能的)。是否可以强制发送方恰好发送 X 个字节,或者如果不可能的话甚至 return 一个错误? (即,接收方要么得到 X 字节的数据包,要么得不到数据包)。

编辑: 如果发送的字节数始终为 X,那么为什么 return 值(发送的字节数)可能小于发送数据的字节数(如 https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-sendto ) 并且是非负的?

That means, it cannot receive a packet of less than X bytes (which is possible if sendto returns less than X bytes).

这永远不会发生在 UDP 套接字上。来自 the send(2) manual page:

If the message is too long to pass atomically through the underlying protocol, the error EMSGSIZE is returned, and the message is not transmitted.

简而言之,默认情况下您要求的行为已经存在。