UDP
User Datagram Protocol
UDP
User Datagram Protocol is a fast, connectionless transport protocol.
UDP Basics
- Connectionless: No connection setup required
- Stateless: No connection state maintained
- Unreliable: No delivery guarantee
- Fast: Minimal overhead
- Datagram-based: Fixed-size packets
When to Use UDP
Perfect For
- Live video/audio streaming
- Online gaming
- VoIP (Voice over IP)
- DNS queries
- DHCP
- NTP (Network Time Protocol)
- Real-time applications
Why UDP?
- Speed is critical
- Occasional packet loss acceptable
- Low latency required
- Many simultaneous connections
UDP Packet Structure
Source Port (16 bits)
Destination Port (16 bits)
Length (16 bits)
Checksum (16 bits)
[Data/Payload]Common UDP Ports
53 - DNS
67, 68 - DHCP
123 - NTP
161, 162 - SNMP
514 - Syslog
1900 - UPnP
5353 - mDNSUDP vs TCP
UDP TCP
No connection setup 3-way handshake
No delivery guarantee Reliable delivery
Out of order possible In-order delivery
Low overhead Higher overhead
Faster Slower
Connectionless Connection-orientedPython UDP Example
Server
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('localhost', 5000))
while True:
data, addr = server.recvfrom(1024)
print(f"Received from {addr}: {data}")
server.sendto(b"Echo: " + data, addr)Client
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b"Hello", ('localhost', 5000))
response, _ = client.recvfrom(1024)
print(response)Network Tools for UDP
# Send UDP packets
nc -u host port
echo "message" | nc -u localhost 5000
# Monitor UDP traffic
tcpdump -i eth0 'udp port 53'
# Check open UDP ports
sudo ss -ulnp
# DNS queries use UDP
nslookup example.com
dig example.com
# DHCP uses UDP
dnsmasq # DHCP server
dhclient # DHCP clientReal-World Applications
DNS (Port 53)
- Domain name to IP address resolution
- Uses UDP for queries
- Falls back to TCP for large responses
DHCP (Ports 67, 68)
- Automatic IP address assignment
- Client broadcasts to find server
- Server responds with IP configuration
NTP (Port 123)
- Network Time Protocol
- Synchronize system clocks
- Critical for logging and security
Syslog (Port 514)
- Remote logging
- Send logs to central server
- Important for monitoring
Best Practices
- Use UDP only when appropriate
- Implement application-level reliability if needed
- Monitor packet loss
- Test with various network conditions
- Use checksums for verification
- Implement timeouts
- Monitor UDP traffic for security
- Don't use for critical data