UDP packet length guaranteed?

Started by
5 comments, last by Brandon N 18 years, 10 months ago
I've used TCP almost exclusively for any network programming I've done, and for the few UDP projects I've worked on, I've never encountered problems with assuming the subject line to be true. But, is it? I know that the actual packet can be in any way malformed, but is it guaranteed to come at the same length as it was sent? If not how does one get back on track in terms of where to start reading the next packet after receiving a longer/shorter message than intended? This would be even worse in a variable length message system.
Advertisement
UDP is a datagram protocol, not a stream protocol; as such, messages are not fragmented when they are received by the application layer. Because it must be encapsulated in an IP packet, it seems staggeringly unlikely that a UDP packet will accidentally change length. Packets that do somehow have an unexpected length, however, should be treated as corrupt and discarded.
Just to be clear - UDP does get fragmented, but this is a side-effect of being in the IP layer, and it should (must!) be de-fragmented by the time it's delivered to your application; so although it is being fragmenetd, there is no way you'd ever know.

So, when reading about firewalls, you will see mention of individual UDP packets coming in as multiple separate packets, and being "re-assembled" - but this is all going on transparently as far as your app is concerned.

It is conceivable that a broken IP stack with a nasty firewall that drops some of the fragments could potentially deliver a partially-de-fragmented packet, but that would definitely be a bug in the IP stack.
IIRC, UDP is pretty reliable in terms of the packets you'll get back from the network layer. Whether a given packet actually arives at its destination is another matter though.

And UDP packet you send should arrive identically at the other end. That means the length will be the same and I'll have the same contents. (Actually, its only a simple checksum used to check the contents, so it could still be corrupt. This is unlikely though).

Only delivery and ordering are not guranteed for UDP.
Ok, those responses answer my questions and concerns. Thank you all.

Two last questions.

First about the checksum. I'm assuming the checksum is done below the application layer, so if it fails is it simply discarded as I suspect?

Second, is it true that when you recvrom() any data not read will be dropped? I.E. There are 10 bytes and you recvfrom( somesock, somebuffer, 5, ... ) the remaining 5 bytes are discarded?

Thanks again for the timely and informative responses.
Yes, the remaining 5 bytes of that datagram would be discarded in your example.
enum Bool { True, False, FileNotFound };
Quote:Original post by hplus0603
Yes, the remaining 5 bytes of that datagram would be discarded in your example.

Terrific, thank you.

This topic is closed to new replies.

Advertisement