Sub topic 1
What a port number identifies
Prerequisites
This chapter assumes you know what an IP address is, understand the client-server model, can run commands in a terminal, and can read a short Python script.
The problem ports solve
An IP address gets a packet to the right host. A host usually runs many network programs at once, such as a web server, an SSH daemon and a mail server. The operating system needs a way to hand each arriving packet to the right program.
A port number does this. It is a 16-bit unsigned integer, from 0 to 65535, carried in the header of each TCP or UDP segment. It identifies an endpoint on a host, and in practice that means one program (or one group of cooperating processes) that has asked the operating system for that port.
A port is not a physical connector. It is a number the operating system uses to look up which program should receive the data.
Source and destination ports
Every TCP and UDP header holds two port numbers: a source port and a destination port. A client sets the destination port to the service it wants, for example 443 for HTTPS. The operating system chooses the source port. The server's reply swaps the two values, so the reply finds its way back to the right client program.
Ports are scoped to a protocol
TCP port 53 and UDP port 53 are separate. A program can listen on TCP 8080 while a different program listens on UDP 8080. A full identification of one end of a conversation therefore has three parts: the IP address, the transport protocol and the port. Together these form a socket address, such as tcp 192.0.2.10:443. A later chapter covers sockets in detail.
Looking up a port by name
Most systems keep a table of service names and default ports. On Linux it is /etc/services. Python can query it:
import socket
for name in ("http", "https", "ssh", "smtp", "domain"):
print(name, socket.getservbyname(name, "tcp"))
print(socket.getservbyport(443, "tcp"))The loop prints each name with its port number (http 80, https 443, ssh 22, smtp 25, domain 53). The last line prints the name for port 443, usually https. If a name or port is missing from the local table, Python raises OSError.
Common mistakes
- Thinking a port identifies a host. It only has meaning together with an IP address.
- Forgetting that TCP and UDP ports are separate. A firewall rule that opens TCP 53 does not open UDP 53.
- Assuming a port number proves which protocol is running. The table gives defaults only, and any program can listen on any free port.
Exercise
A server at 192.0.2.10 runs a DNS service on UDP 53 and an unrelated program on TCP 53. Can both run at the same time? Explain why.
Show answer
Yes. Ports are scoped to the transport protocol, so UDP 53 and TCP 53 are different endpoints. The operating system tracks them separately, so each program gets its own traffic without conflict.