TCP, UDP, ports, and sockets

Send a UDP datagram

Understand one UDP message, its ports and checksum, and the responsibilities left to the application.

A UDP datagram contains source and destination ports, a length, a checksum, and application data. One send produces one datagram, and a receive returns one complete datagram when the buffer is large enough.

UDP has no handshake. A sender can transmit without first proving that the destination application exists. An ICMP error may come back, or there may be no response at all.

Send one message with netcat

The simplest way to feel UDP is netcat. In one terminal, listen on UDP port 5353:

nc -u -l 5353

In another, send a single line:

echo 'hello udp' | nc -u localhost 5353

The listener prints hello udp as one complete message. Stop the listener and send again. The sender exits with no error. Nothing told it the other side was gone. That’s normal UDP behavior.

See the datagram on the wire

Capture one exchange while you send:

sudo tcpdump -ni lo -c 2 udp port 5353
IP 127.0.0.1.41203 > 127.0.0.1.5353: UDP, length 9
IP 127.0.0.1.5353 > 127.0.0.1.41203: UDP, length 9

The length 9 field is the UDP header plus payload. The ephemeral source port 41203 was chosen by the kernel. The destination port 5353 is where you told the listener to wait.

What the application must handle

DNS often uses UDP for ordinary queries. Real-time applications also use UDP when late data can be less useful than missing data. These applications define any needed retries, ordering, and rate control themselves.

“UDP is faster” is too simple. It offers fewer built-in services; whether that helps depends on the protocol designed above it and the network conditions. If your application needs delivery guarantees, build them explicitly or use TCP instead.

Try sending to a port where nothing listens. You may see an ICMP “port unreachable” message in the capture, or you may see nothing at all. Both outcomes are normal. The difference is why application protocols on top of UDP define their own timeouts and retries.

Lesson completed