TCP, UDP and ports · Computer Networks
How do two programs hold a reliable conversation over an unreliable network?
Course contentsWhy you need it
Packets get lost, duplicated and reordered all the time. TCP hides that and gives programs a reliable stream; UDP skips the guarantees for speed. Ports let one machine run many services at once. Every "connection refused" or "connection timed out" error is about these.
The intuition
An address finds the machine; a port (0–65535) finds the program on it. Well-known ones: 22 SSH, 53 DNS, 80 HTTP, 443 HTTPS, 5432 PostgreSQL.
TCP opens with a three-way handshake: SYN ("can we talk?"), SYN-ACK ("yes, can you hear me?"), ACK ("yes"). After that each piece of data is numbered (a sequence number); the receiver acknowledges what arrived, puts pieces back in order, and the sender resends anything not acknowledged.
UDP just sends. Good when late data is useless anyway: video calls, games, DNS lookups.
Definition
Port
A number from 0 to 65535 that picks one program on a machine. A server listens on a port; a client connects to address:port.
TCP and UDP
TCP: connection, ordering, retransmission, flow control. UDP: single datagrams, no guarantees, less delay.
Examples
Put the pieces back in order
Try it yourselfSegments arrive out of order and one is duplicated. Sequence numbers fix both.
arrived = [(3, "lo w"), (1, "hel"), (4, "orld"), (3, "lo w"), (2, "")]
received = {}
for seq, data in arrived:
if seq in received:
print("duplicate", seq, "ignored")
continue
received[seq] = data
message = "".join(received[s] for s in sorted(received))
print(message)- L4Seen this number already: drop it.
duplicate 3 ignored - L8Order by sequence number, not by arrival.
- L9In order, without the duplicate.
hello world
Which piece is missing?
Try it yourselfThe receiver acknowledges the next number it expects. The sender resends from there.
got = {1, 2, 4, 5}
expected = 1
while expected in got:
expected += 1
print("ACK", expected)- L31 and 2 are here, 3 isn't.
- L5"Send me 3 next": 4 and 5 wait until 3 arrives.
ACK 3
Common mistakes
Refused versus timed out
Connection refused: the machine answered, but nothing listens on that port (service down, wrong port). Timed out: no answer at all (firewall, wrong address, machine down).
TCP is always better
Retransmitting a lost video frame that's already too late makes a call worse. Real-time traffic often prefers UDP.
Quick quiz
1. A web server runs on the machine, but `curl http://host:8080` says "connection refused". Most likely?
Show the answer
Answer: A
Refused means the machine replied: it's reachable, but no program accepted on that port.
2. What does this print?
handshake = ["SYN", "SYN-ACK", "ACK"]
for i, msg in enumerate(handshake, 1):
sender = "client" if msg != "SYN-ACK" else "server"
print(i, sender, msg)Show the answer
Answer: A
The client starts, the server answers, the client confirms.
Practice
3 exercises in three steps: predict what a program prints, change a program to meet a new requirement, then write one from scratch. Your code runs in the browser and is checked the moment you submit.
- PredictReassemble
Type exactly what this program prints.
- ModifyName the service
service(port)should name well-known ports. Add HTTPS (443), SSH (22) and PostgreSQL (5432, return"postgres"), and return"unknown"for anything else instead of crashing. - WriteCumulative ACK
Write
next_ack(received)that takes a list of sequence numbers that arrived (in any order, maybe with duplicates, starting from 1) and returns the next number the receiver should ask for: the smallest positive number missing.
Practise this lesson
Open the interactive lesson to edit and run these examples and solve the exercises with instant feedback. Free to start, no sign-up.
Interactive lessons open in order. If you have not done the earlier ones yet, you start at the course map.
Terms in this lesson
| Term | Chinese | Definition |
|---|---|---|
| Port number | 端口号 | A number that selects a program on a machine, such as 443 for HTTPS. |
| TCP | 传输控制协议 | A reliable, ordered byte stream between two programs. |
| UDP | 用户数据报协议 | Single messages with no delivery guarantee and little delay. |
| Three-way handshake | 三次握手 | SYN, SYN-ACK, ACK: how a TCP connection starts. |