Are datagrams always received completely?
Asked Answered
A

2

14

Most datagram receiving functions such as c's recv or read, javas DatagramPacket class or pythons SocketServer, include the possibility to find out the amount of received data.

c:

int amount = recv(sock, buf, n, MSG_WAITALL);

java:

int amount = datagramSocket.getLength();

python:

class MyUDPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        amount = len (self.request[0])

Are these reliable? Or is it possible that only parts of the message are received, due to for example packet fragmentation or network delay?
In other words: When I send a variable length chunk of data via udp and receive it at the other end, are these amount values exactly equal to the size of the original chunk?

Edit:
ninjalj made a good point and I want to include it here. What happens when the receiving function is interrupted, for instance by a signal? What happens when two threads simultaneously try to receive from the same socket?

Apeak answered 28/10, 2011 at 15:57 Comment(1)
just fyi, your java code has a grave miss-spelling of 'Length'Erase
S
14

UDP datagrams cannot be partially delivered¹; they are delivered as-is or not at all. So yes, you can be sure that the received datagram was sent exactly as you see it on the receiver's end.

Edit to incorporate Will's comment which is the best kind of correct (i.e., technically):

¹They can be fragmented at the IP level, but the network stack on the receiver side will either fully reassemble a datagram and pass it to the listening process as sent, or will not acknowledge that any data at all has been received.

Schexnayder answered 28/10, 2011 at 16:0 Comment(3)
Technically large packets can be fragmented, but the protocol handles the fragmentation and reassembly and if it cannot be reassembled completely it's marked as lost, so the user will never notice.Hawkie
Will is correct. The UDP stack in the OS takes care of the fragmentation but fragmentation is a IP level task. So it applies to both TCP and UDP equally. That being said UDP packets are not guaranteed delivery. So any retransmissions needs to be taken care by your program.Athene
Though, if your buffer to recv() is not big enough to hold the packet, you will get truncated data.Circumambulate
M
4

Partial datagrams are only permissible with UDP Lite.

Mountford answered 6/11, 2011 at 2:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.