Udp數據發送最大長度問題討論
1. 問題描述
在使用udp進行編程時,遇到這樣一個問題:利用Udp進行發送視頻數據,會出現發送失敗的情況,具體現象如下:
1.1 widows下打印相關的錯誤輸出:
func UdpClient::Send line 114 sendto err errno is 10040
通過查閱相關文檔可知具體的錯誤原因:
WSAEMSGSIZE
10040 (0x2738)
A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself.
10040 一個在數據報套接字上發送的消息大於內部消息緩衝器或其他一些網絡限制,或該用戶用於接收數據報的緩衝器比數據報小。
1.2 Linux下打印相關的錯誤輸出:
func Send line 102 sendto err errno is 90 Message too long
#define EMSGSIZE 90 /* Message too long */
2. 問題追蹤
編寫UDP測試程序,從出現問題的數據長度依次進行遞減直到 udp sendto能發送成功,
代碼片段如下:
#define UDP_DATA_MAX_LEN 65535
unsigned char test[UDP_DATA_MAX_LEN] = fly in coding udp test";
while(1)
{
if(UdpClientTest.Send(test,UDP_DATA_MAX_LEN - i) < 0)
{
i++;
continue;
}
else
{
printf("i %d \n",i);
}
}
window下運行如下:
func UdpClient::Send line 114 sendto err errno is 10040
i 28
Linux下運行如下:
func Send line 102 sendto err errno is 90 Message too long
i 28
通過定位可以發現無論在windows下還是在Linux下,udp能發送的最大長度是 (65535 - 28)
3. udp數據包分析
UDP數據報封裝成一份IP數據報的格式如下圖
IP首部
udp首部
通過上述幾張圖就可以知道爲什麼是 65535 -28 了