UDP数据包数据长度的实际限制是多少?

What's the practical limit for the data length of UDP packet?

这是维基百科对UDP长度字段的解释header:

Length
A field that specifies the length in bytes of the UDP header and UDP data. The minimum length is 8 bytes because that is the length of the header. The field size sets a theoretical limit of 65,535 bytes (8 byte header + 65,527 bytes of data) for a UDP datagram. The practical limit for the data length which is imposed by the underlying IPv4 protocol is 65,507 bytes (65,535 − 8 byte UDP header − 20 byte IP header).

数据长度的实际限制应该减去 20 字节 IP header,这是为什么?

因为UDP数据包封装在IP数据包中,IP数据包头是20字节。如果没有封装的 IP 数据包,您将无法发送 UDP 数据包。通常实际限制要小得多,它取决于传输 UDP 数据包的两个端点之间路由器的 MTU。

因为 IP header 必须 (a) 发送和 (b) 计算在 16 位长度的字中。参见 RFC 791 #3.1

然而,实际实际限制通常被接受为 534 字节,以避免在 IP 层分片,从而增加数据报丢失的风险。

好好看看这个link对IPheader的解释: https://www.ietf.org/rfc/rfc791.txt

我引用: 总长度:16 位

Total Length is the length of the datagram, measured in octets, including internet header and data. This field allows the length of a datagram to be up to 65,535 octets. Such long datagrams are impractical for most hosts and networks. All hosts must be prepared to accept datagrams of up to 576 octets (whether they arrive whole or in fragments). It is recommended that hosts only send datagrams larger than 576 octets if they have assurance that the destination is prepared to accept the larger datagrams. The number 576 is selected to allow a reasonable sized data block to be transmitted in addition to the required header information. For example, this size allows a data block of 512 octets plus 64 header octets to fit in a datagram. The maximal internet header is 60 octets, and a typical internet header is 20 octets, allowing a margin for headers of higher level protocols.

因此最大总长度为 65535,但这包括 IP header 本身。 因此,您的 IP 负载可以是 65535 - 20 = 65515.

但是在您的情况下,IP 的有效负载是 UDP,而 UDP 有一个 header 自己的 8 字节。因此,您达到了 UDP 数据包有效载荷的 theoretical 限制:65,535 − 8 字节 UDP header − 20 字节 IP header

注意使用理论而不是实际。 UDP数据包的实际限制考虑了分片的可能性,因此考虑了网络层的mtu。上面的 link 也有一个有趣的句子,其中包含值 576。576 - 20 - 8 = 548 不完全是 534,但接近了。这或许可以解释这个实际限制。