Sub topic 2
Sockets and ports: how programs talk over the network
This chapter assumes you know the four-layer model (application, transport, network, link), the idea of encapsulation, and basic Python. It covers how a program uses the transport layer through the socket API, how ports identify programs, and how a TCP client and server call the API.
What a socket is
A socket is an operating-system object that a program uses as an endpoint for network communication. The program reads from it and writes to it, and the operating system handles the transport protocol underneath.
The network layer delivers a packet to a host, identified by an IP address. A host runs many programs at once, so the transport layer needs a second address to pick the right program. That address is the port number, a 16-bit unsigned integer from 0 to 65535.
An endpoint is the pair (IP address, port). In Python, the pair is written as a tuple such as ("127.0.0.1", 5000).
Port ranges
| Range | Name | Typical use |
|---|---|---|
| 0 to 1023 | Well-known ports | Standard services: HTTP 80, HTTPS 443, DNS 53, SSH 22, SMTP 25 |
| 1024 to 49151 | Registered ports | Applications registered with IANA |
| 49152 to 65535 | Dynamic (ephemeral) ports | Short-lived client-side ports chosen by the OS |
On most systems, binding to a well-known port requires administrator privileges. A client usually does not choose its port. The operating system assigns an unused ephemeral port when the client connects.
Multiplexing means gathering data from several sockets and passing it to the network layer, with port numbers written in the transport header. Demultiplexing means using the destination port in an arriving segment to deliver the data to the correct socket.
How sockets are identified
The identification rule differs between UDP and TCP, and GATE tests it often.
- UDP: a socket is identified by the pair (destination IP, destination port). Segments from two different clients that carry the same destination IP and port go to the same socket.
- TCP: a connection is identified by the 4-tuple (source IP, source port, destination IP, destination port). Two clients connecting to port 80 on one server get different connection sockets, because their source addresses or source ports differ.
This is why a web server can hold thousands of simultaneous connections on port 80. The server's port number is the same for all of them. The 4-tuple is different for each.
Socket types
When a program creates a socket, it chooses an address family and a type.
AF_INETselects IPv4.AF_INET6selects IPv6.SOCK_STREAMselects TCP, a reliable, ordered byte stream.SOCK_DGRAMselects UDP, which sends independent datagrams.
A TCP socket delivers a stream of bytes with no message boundaries. If a sender calls sendall twice, the receiver might get the data in one recv call or in many. The program has to mark message boundaries itself, for example with a length prefix or a delimiter.
The TCP call sequence
A TCP server and client use different calls. The server prepares to receive connections, and the client starts one.
| Step | Server | Client |
|---|---|---|
| 1 | `socket()` creates a socket | `socket()` creates a socket |
| 2 | `bind()` attaches the socket to an IP and port | (optional) |
| 3 | `listen()` marks the socket as passive | |
| 4 | `accept()` blocks until a connection arrives | `connect()` starts the three-way handshake |
| 5 | `recv()` and `send()` on the new socket | `send()` and `recv()` |
| 6 | `close()` | `close()` |
The server has two kinds of sockets. The listening socket stays bound to the well-known port and only accepts new connections. Each accept() call returns a new connection socket, which carries the data for one client. Because of this, the server can keep listening while it talks to existing clients.
The three-way handshake takes place inside connect() on the client and completes before accept() returns on the server. The next chapters cover the handshake itself.
Worked example: a TCP echo server and client
The server below receives one message and sends it back. Run it first, then run the client in a second terminal.
import socket
# Server: run this first, then run the client in another terminal.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
server.bind(("127.0.0.1", 5000))
server.listen()
conn, addr = server.accept()
with conn:
data = conn.recv(1024)
conn.sendall(data)import socket
# Client
with socket.create_connection(("127.0.0.1", 5000)) as client:
client.sendall(b"hello")
print(client.recv(1024))The client prints b'hello'. In the server, addr holds the client's address, such as ('127.0.0.1', 54218), where the second value is the ephemeral port the OS picked. The helper create_connection performs the socket and connect steps, and it resolves host names as well.
Common errors
- Address already in use. After a server exits, the OS can keep the port in a closing state (TIMEWAIT) for a while. Restarting the server then fails at
bind(). Calling `server.setsockopt(socket.SOLSOCKET, socket.SO_REUSEADDR, 1)beforebind()` avoids this during development. - Connection refused. The client ran before the server, or no process is listening on that port. The server's operating system answers the connection attempt with a reset.
- Assuming one
recvequals onesend.recv(1024)returns up to 1024 bytes, possibly fewer. A loop that reads until a known length or delimiter is the correct pattern. - Binding to the wrong address.
127.0.0.1accepts only local connections. The address0.0.0.0accepts connections on every interface of the host. - Using
sendand ignoring its return value.sendmay transmit only part of the data.sendallrepeats until everything is sent.
Names to addresses
Programs usually have a host name rather than an IP address. The function getaddrinfo asks the operating system's resolver, which queries DNS, and returns the addresses a client could connect to for the given host and port.
import socket
for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(
"example.com", 80, type=socket.SOCK_STREAM):
print(family.name, sockaddr)The output has one line per address, for example AF_INET6 for an IPv6 address and AF_INET for an IPv4 address. Later chapters follow the DNS lookup in detail.
A socket-level HTTP request
HTTP is a text protocol carried on a TCP byte stream, so a socket program can speak it directly. The code below sends a hand-written HTTP/1.1 request and prints the status line.
import socket
host = "example.com"
request = (
f"GET / HTTP/1.1\r\n"
f"Host: {host}\r\n"
f"Connection: close\r\n"
f"\r\n"
)
with socket.create_connection((host, 80)) as s:
s.sendall(request.encode())
response = b""
while True:
chunk = s.recv(4096)
if not chunk:
break
response += chunk
print(response.split(b"\r\n")[0].decode())The loop reads until recv returns an empty byte string. That signals that the server closed its side of the connection, which the Connection: close header asked it to do. The first line printed is typically HTTP/1.1 200 OK.
UDP sockets, briefly
A UDP program skips listen, accept, and connect. The server calls bind() and then recvfrom(), which returns the data and the sender's address. The client calls sendto() with the destination address. No handshake happens, and each datagram is delivered whole or not at all. The next chapter covers UDP in detail.
GATE-style points to remember
- A port is 16 bits, so there are 65536 possible values.
- A TCP connection is identified by four values. A UDP socket is identified by two.
- The server's
accept()returns a new socket. The listening socket is not used for data. - The server calls
bind,listen, andaccept. The client callsconnect. - The three-way handshake occurs during
connect. - Well-known ports run from 0 to 1023.
Exercise
A web server listens on port 80. Client X (IP 192.168.1.5) opens two TCP connections to it from source ports 40000 and 40001. Client Y (IP 192.168.1.6) opens one connection from source port 40000. How many connection sockets does the server hold, and why does the server not confuse the two connections that use source port 40000?
Show answer
The server holds three connection sockets, plus the listening socket. The two connections that use source port 40000 differ in source IP (192.168.1.5 versus 192.168.1.6), so their 4-tuples (source IP, source port, destination IP, destination port) are different. TCP demultiplexes on all four values, not only the destination port.
Exercise
A UDP server is bound to port 9000. Two clients send datagrams to it from different source IPs and source ports. How many UDP sockets on the server receive these datagrams?
Show answer
One. A UDP socket is identified by (destination IP, destination port), so both datagrams are delivered to the same socket. The application reads the sender's address from the result of recvfrom() to tell the clients apart.
Exercise
A client calls send() three times with 100 bytes each time. The server then calls recv(1024) once. Can the server receive 300 bytes in that call? Can it receive 100 bytes? Explain.
Show answer
Yes to both. TCP is a byte stream with no message boundaries. The three writes may arrive together, so one recv can return all 300 bytes. It may also return only the first 100, and the server then needs further recv calls for the rest.