udp-header
tcp-header
UDP
由于udp报文头中使用16bits表示长度,因此最大长度是2的16次方减1,由于udp的报文头是8个字节,IP报文头最小20字节, 因此udp报文发送的最大长度是65536 - 1 - 8 - 20,使用程序验证:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>

int main(int argc, char *argv[])
{
    struct sockaddr_in srvAddr;
    bzero(&srvAddr, sizeof(srvAddr));
    srvAddr.sin_family = AF_INET;  
    srvAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    srvAddr.sin_port = htons(8888);

    int iSock = socket(AF_INET, SOCK_DGRAM, 0); // udp
    char szBuf[1024 * 64 - 1 - 20 - 8] = {0};
    int iRet = sendto(iSock, szBuf, sizeof(szBuf), 0, (struct sockaddr *)&srvAddr, sizeof(srvAddr));
    printf("send size is %d, iRet is %d, errmsg[%s]\n", sizeof(szBuf), iRet, strerror(errno));
    
    close(iSock);
    return 0;

}

运行结果:

[root udp]#./udp-client
send size is 65507, iRet is 65507, errmsg[Success]

如果我们把szBuf的长度增加1,编译运行结果:

[root udp]#./udp-client
send size is 65508, iRet is -1, errmsg[Message too long]