Sub topic 2
Sockets and ports: how programs talk over the network
Prerequisites and working model
Assume you know the layered network model, IP addresses, bandwidth, latency, and basic Python. This chapter focuses on the socket API, the programming interface that lets an application use TCP or UDP.
A socket is an endpoint for network communication. For an Internet socket, the endpoint is commonly identified by:
\[ (\text{IP address}, \text{port number}) \]
An IP address identifies a host or network interface. A port identifies a process or service on that host. Port numbers range from 0 through 65,535. A TCP connection is identified by a four-tuple:
\[ (\text{source IP}, \text{source port}, \text{destination IP}, \text{destination port}) \]
The same server port can support many clients because each client has a different source address or source port.
TCP socket call sequence
TCP provides a reliable, connection-oriented byte stream. A server usually follows this sequence:
socket()creates a socket object.bind()assigns a local IP address and port.listen()changes the socket into a passive listening socket.accept()waits for a client. It returns a new connected socket.recv()andsendall()exchange bytes.close()releases the connection.
The listening socket remains available for later clients. The connected socket returned by accept() represents one particular TCP connection.
A client usually calls socket() and then connect(). The connect() operation starts TCP connection setup, including the three-way handshake. After that, both sides can send and receive data.
import socket
import sys
HOST = "127.0.0.1"
PORT = 5000
if len(sys.argv) != 2 or sys.argv[1] not in {"server", "client"}:
raise SystemExit("usage: python echo.py server|client")
if sys.argv[1] == "server":
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind((HOST, PORT))
listener.listen(1)
print("waiting for a client")
with listener.accept()[0] as connection:
data = connection.recv(1024)
connection.sendall(data)
else:
with socket.create_connection((HOST, PORT)) as connection:
connection.sendall(b"hello")
print(connection.recv(1024).decode())Run python echo.py server in one terminal, then run python echo.py client in another. The address 127.0.0.1 means “this same computer.” The operating system chooses an unused temporary source port for the client.
TCP is a byte stream, so one sendall() call does not guarantee one matching recv() call. An application protocol must define message boundaries, such as a fixed length, a delimiter, or a length field.
UDP sockets
UDP is connectionless. A program normally uses bind() to receive datagrams and sendto() or recvfrom() to include the destination or source address with each message. UDP does not establish a connection, retransmit lost data, or guarantee ordering. It has lower protocol overhead, but the application must handle any required reliability.
| Property | TCP | UDP |
|---|---|---|
| Communication model | Connection-oriented byte stream | Connectionless datagrams |
| Delivery | Reliable and ordered | Best effort |
| Typical API | `connect`, `accept`, `send`, `recv` | `sendto`, `recvfrom` |
Visualizing the endpoints
Exercise
A server is bound to 192.0.2.10:8080. Two clients connect from 198.51.100.4:40000 and 198.51.100.5:40000. Can the server distinguish the connections?
Show answer
Yes. Their four-tuples differ in source IP address, even though their source and destination port numbers are the same.