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
1
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
2
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
1
Create socket
Initialize a socket using the appropriate system call. The socket acts as an endpoint for network communication.
2
Bind to address
Associate the socket with a specific IP address and port number. This step is typically done on the server side.
3
Listen for connections
For TCP servers, put the socket in listening mode to accept incoming connection requests.
4
Accept connections
Accept incoming client connections, creating a new socket for each connection.
5
Send and receive data
Exchange data between client and server using send/receive operations.
6
Close connection
Properly close the socket when communication is complete.
UDP socket workflow
1
Create socket
Initialize a UDP socket for datagram communication.
2
Bind to address
Bind the socket to an address and port (server side).
3
Send and receive datagrams
Use sendto() and recvfrom() to exchange messages without establishing a connection.
4
Close socket
Close the socket when done.
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