Introduction
Socket programming forms the foundation of network communication. Understanding how to work with TCP and UDP sockets is essential for building networked applications from scratch.This is part of Week 1 – Networking from Scratch in the “From CPU to the Browser” course.
Socket types
TCP sockets
Transmission Control Protocol (TCP) provides reliable, ordered, and error-checked delivery of data between applications. TCP sockets establish a connection before data transfer and maintain that connection throughout the communication.Key characteristics:
- Connection-oriented protocol
- Guaranteed delivery and ordering
- Flow control and congestion control
- Higher overhead than UDP
UDP sockets
User Datagram Protocol (UDP) is a connectionless protocol that sends messages (datagrams) without establishing a connection. It’s faster but doesn’t guarantee delivery or ordering.Key characteristics:
- Connectionless protocol
- No delivery guarantees
- Lower latency and overhead
- Suitable for real-time applications
TCP socket workflow
Create socket
Initialize a socket using the appropriate system call. The socket acts as an endpoint for network communication.
Bind to address
Associate the socket with a specific IP address and port number. This step is typically done on the server side.
Listen for connections
For TCP servers, put the socket in listening mode to accept incoming connection requests.
UDP socket workflow
Send and receive datagrams
Use sendto() and recvfrom() to exchange messages without establishing a connection.
Use cases
TCP use cases
- Web servers (HTTP/HTTPS)
- Email protocols (SMTP, IMAP)
- File transfer (FTP)
- Any application requiring reliable delivery
UDP use cases
- Video streaming
- Online gaming
- DNS queries
- VoIP applications
Network debugging tools
When working with sockets, these tools are essential for debugging:- tcpdump: Command-line packet analyzer for capturing network traffic
- Wireshark: GUI-based network protocol analyzer with powerful filtering capabilities
- Network simulation: Tools to simulate latency and packet loss for testing
Next steps
TCP basics
Learn about the three-way handshake, flow control, and HTTP parsing