UDP recv/recvfrom multiple senders

梦想与她 提交于 2019-12-04 13:40:32
INS

No, a UDP message cannot be split. They arrive as they were sent. Also, multiple UDP messages are NOT concatenated.

So N sendto messages correspond to N recvfrom calls.

Quote from wiki:

Datagrams – Packets are sent individually and are checked for integrity only if they arrive. Packets have definite boundaries which are honored upon receipt, meaning a read operation at the receiver socket will yield an entire message as it was originally sent.

You are correct that a single call to recvfrom() will return at most one UDP datagram. But there is no guarantee that each datagram will actually arrive.

In particular, if the UDP datagram that you send is too large, it can become split into pieces at the network level (fragmentation) which increases the likelihood that the datagram will be dropped (because the loss of any fragment causes the loss of the whole). You don't see fragmentation at the application level because the network level reassembles the packet for you.

Things can get very tricky because it is impossible to know in advance exactly how large is too large. There are various algorithms for finding out, but they all amount to trial and error. Worse, firewalls, routers, and operating systems can (and often do) change their behavior toward fragmented datagrams over time. There can be scenarios where a packet of a particular size or composition will always be dropped because it violates some firewall rule.

So never assume that a sendto() will necessarily result in a recvfrom(), and try to keep your datagrams small (less than 1400 bytes is fairly safe, less than 512 bytes is very safe).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!