← Back to all lessons

02 / Networks / 25 min READ + PRACTICE

UDP and protocol design.

Compare datagrams with TCP streams and design a tiny bounded request/response format.

Practice boundaryUse your own devices, your isolated practice VM or 127.0.0.1. Get explicit authorization for any other system.

Datagrams have boundaries

UDP preserves an individual message boundary but does not promise delivery, order or uniqueness. DNS and other protocols add their own transaction IDs, timeouts and retry rules. Use it when the application can handle missing responses.

Inspect rather than assume

Build a localhost-only UDP receiver that prints datagram size and sender address. A sender can send two short messages and compare how receive calls differ from a TCP stream. Set a small maximum payload and timeout.

LAB TERMINAL / EXAMPLE
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('127.0.0.1', 9002))
s.settimeout(3)
try:
    message, peer = s.recvfrom(256)
    print(peer, message.hex())
finally:
    s.close()

Design a response contract

Try a JSON object containing a request ID and a short value. Reject oversized or malformed messages and document what the client should do when a reply is missing. Never treat a sender address alone as authentication.

HANDS-ON EXERCISE

Try it in your lab

Send a short datagram to 127.0.0.1:9002 from a second Python shell and note what happens when the receiver is not running.

CHECKPOINT

Make sure it clicks

How would you distinguish a missing UDP reply from a slow reply?

TRY WITH OPENCODE

A prompt you can adapt

Help me write tests for a local UDP protocol parser with malformed JSON and oversized datagrams.
How to set up OpenCode ↗
Your progress stays in this browser only.