I checked the maximum UDP packet size and saw it is 65507 bytes of data.
Which is 65535-8 (udp headers) - 20 (ip headers).
The UDP length header is 2 bytes long which is 65535 limit.
I understand that we substract 8 from it because its the size of the UDP header
but if it is always 8 why do we need to substract it.
Same question for the 20 of the ip headers length.
Thank you
UDP datagrams are encapsulated inside IP packets. If you are using 20 as the IP packet header size then you mean IPv4, and the minimum IPv4 header size is 20. IPv4 has a theoretical maximum packet size of 65,535 (a 16-bit total length field in the IPv4 header), but the real IPv4 maximum packet size will be the MTU on the link. This size includes the IPv4 header and the IPv4 payload, which will be the UDP datagram, including the UDP header and UDP payload.
Since the UDP datagram is the data of the IPv4 datagram, and the entire length of the IPv4 datagram, including the IPv4 header, is a 16-bit Total Length field of the IPv4 header, the entire IPv4 packet, including the IPv4 header is a maximum of 65,535 octets. This is detailed in the definition of IPv4, RFC 971 Internet protocol, Section 3.1 Internet Header Format:
The definition of the Total Length field is:
That means you must subtract the IPv4 header length from the maximum of 65,535 to arrive at the maximum UDP datagram length, which includes the 8 octet UDP header.