Everyone Can Learn Program
中文 Start learning
Core · NetworksLesson 3 of 6Free to read

TCP, UDP and ports · Computer Networks

How do two programs hold a reliable conversation over an unreliable network?

Course contents

Why 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 yourself

Segments 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)
Step by step
  1. L4Seen this number already: drop it.duplicate 3 ignored
  2. L8Order by sequence number, not by arrival.
  3. L9In order, without the duplicate.hello world

Which piece is missing?

Try it yourself

The 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)
Step by step
  1. L31 and 2 are here, 3 isn't.
  2. 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?

  1. ANothing listens on port 8080
  2. BDNS is broken
  3. CThe cable is unplugged
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)
  1. A
    1 client SYN
    2 server SYN-ACK
    3 client ACK
  2. B
    1 server SYN
    2 client SYN-ACK
    3 server ACK
  3. C
    1 client SYN
    2 client SYN-ACK
    3 server ACK
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.

  1. PredictReassemble

    Type exactly what this program prints.

  2. 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.

  3. 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

TermChineseDefinition
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.