Computing Foundations › How the Internet Works › Day 17

Day 17: TCP, UDP, and Ports

Day 17 of 365 — TCP, UDP, and Ports

After this lesson you will be able to explain how data reaches the right program on a host — through ports, TCP, and UDP — and use that model to see which ports your machine is listening on and to diagnose a "connection refused" in seconds.

Course
Computing Foundations
Category
How the Internet Works
Reading time
≈ 40 min
Practical time
≈ 30 min
Lesson duration
1h 10m
Last verified
2026-07-12

Hands-on lab for this lesson

Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/computing-foundations/day-017-tcp-udp-and-ports

  1. Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
    git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git
    cd ai-roadmap-365.github.io
  2. Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
    cd labs/sections/computing-foundations/day-017-tcp-udp-and-ports
  3. Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
  4. Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
    bash tests/run_tests.sh   # or the test command named in the lab README

You can also open the lab as a local page (works offline, shows the file tree and expected output).

Learning objectives

By the end of this lesson you will be able to:

Prerequisites

Why this matters


The idea in plain language

Diagram: how an address, a port and a socket narrow delivery to one program


Historical background


What it is — and what it is not

They are not:


Why it was created and what problems it solves


How it works

Ports: one number per service

Diagram: well-known ports compared with ephemeral ports

RangeNameMeaningExamples
0–1023Well-knownStandard services; usually need admin rights to open22 SSH, 53 DNS, 80 HTTP, 443 HTTPS
1024–49151RegisteredAssigned to applications on request3306 MySQL, 5432 PostgreSQL, 6379 Redis, 8080 alt-HTTP
49152–65535EphemeralTemporary numbers the OS hands to clientsyour browser’s outgoing side

The socket: host plus port

Diagram: one host running multiple services on different ports, with a socket shown as a host and port pair

TCP: the handshake

Flowchart: the TCP three-way handshake between a client and a server

  1. SYN. “Can we talk? I will start counting from x.”
  2. SYN-ACK. “Yes, I heard you. I will start counting from y.”
  3. ACK. “Got it — let’s go.” The connection is established.

Once established, TCP delivers four guarantees:

UDP: send and forget


An everyday analogy

Diagram: how the four-tuple distinguishes simultaneous connections to one port

An office building with a switchboard.

The buildingThe network
The street addressThe IP address
The extension numberThe port
The switchboardThe kernel, routing to sockets
”Extension 443, please”Connecting to a service
A registered call, both parties confirmedTCP
A note pushed under the doorUDP

Examples in practice

Diagram: a refused connection compared with one that hangs

Diagram: what TCP guarantees compared with what UDP gives up


Implications: security, privacy, performance, scalability, and cost

Diagram: binding to loopback compared with binding to all interfaces


Alternatives: free, open source, and commercial

ToolTypeWhat it tells you
lsof -iFree, built inWhich process holds which port
ss / netstatFree, built inEvery socket, and its state
nc (netcat)Free, built inWhether a port answers, and what it says
nmapFree, open sourceWhich ports are open on a host you own
tcpdumpFree, built inThe packets themselves
WiresharkFree, open sourceThe same, decoded and readable

TermWhat it actually is
PortA 16-bit number identifying a program on a host
SocketA program’s bound endpoint: address plus port
ConnectionThe four-tuple of both addresses and both ports
TCPReliable, ordered, congestion-controlled byte stream
UDPUnreliable, unordered datagrams with almost no machinery
QUICTCP-like guarantees rebuilt on top of UDP

When to use it — and when not to

Diagram: the four guarantees TCP provides


The AI connection

Diagram: how QUIC rebuilds reliability on top of UDP


Knowledge check

quiz:
  question: "Connecting to a service gives \"connection refused\" from one machine and simply hangs from another. What does the difference tell you?"
  options:
    - "The refusal means the host answered with nothing listening; the hang means packets are being dropped, typically by a firewall"
    - "The refusal means the port is firewalled; the hang means the service is overloaded"
    - "Both indicate the same failure, and the difference is only in client timeout settings"
    - "The refusal means DNS failed; the hang means the route to the host is missing"
  answer_index: 0
  explanation: "A refusal is an active reply: the machine is reachable and no program holds that port. A hang means nothing replies at all, which is what a firewall configured to drop rather than reject produces — deliberately, so a scanner learns nothing."

Hands-on exercise

Diagram: the steps to diagnose a port already in use

Find what is listening, then open a port yourself and connect to it. Worked through fully in the Day 17 lab directory.

What you are doingCommand
See every listening socketss -tlnp or lsof -iTCP -sTCP:LISTEN
Find what holds one portlsof -i :8080
Start a server on a portpython3 -m http.server 8080
Connect to itcurl http://127.0.0.1:8080/
Check a port without a clientnc -vz 127.0.0.1 8080
Watch the handshakesudo tcpdump -i lo0 -c 6 port 8080
Cause the classic errorStart a second server on the same port

Expected output

COMMAND   PID   USER   FD  TYPE  NAME
python3  4812    you    3u IPv4  *:8080 (LISTEN)
Connection to 127.0.0.1 port 8080 [tcp/http-alt] succeeded!
OSError: [Errno 48] Address already in use

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. What does a port number identify?

  1. A physical socket on the back of the computer
  2. A specific service on a host, so one machine can run many
  3. The physical route a packet takes across the Internet
  4. The encryption key used to secure a connection
Show answer

Answer: B. A specific service on a host, so one machine can run many

An IP address gets data to the right host; a port (0–65535) gets it to the right program on that host, which is how a single machine can run a web server, a database, and a login service at the same time.

Q2. Which three messages make up the TCP three-way handshake, in order?

  1. ACK, SYN, SYN-ACK
  2. SYN, ACK, SYN-ACK
  3. SYN, SYN-ACK, ACK
  4. PING, PONG, ACK
Show answer

Answer: C. SYN, SYN-ACK, ACK

The client sends SYN ("can we talk, I start at x"), the server replies SYN-ACK ("yes, got x, I start at y"), and the client sends ACK ("got y, let's go"), after which the connection is established.

Q3. Which of these is a guarantee TCP provides but UDP does not?

  1. Encryption of the data payload end to end
  2. Faster delivery with no connection setup cost
  3. Hiding which IP addresses are communicating
  4. Retransmission of lost packets, so data arrives in order
Show answer

Answer: D. Retransmission of lost packets, so data arrives in order

TCP numbers every byte, acknowledges what arrives, and retransmits what is lost, delivering data reliably and in order. UDP does none of this. Neither protocol encrypts data — that is TLS's job.

Q4. Why is UDP a good fit for DNS lookups and live video?

  1. It is connectionless and low-overhead, and they tolerate loss
  2. Because it guarantees every packet arrives in order
  3. Because it encrypts each packet automatically
  4. Because it uses well-known ports below 1024
Show answer

Answer: A. It is connectionless and low-overhead, and they tolerate loss

UDP skips the handshake and reliability machinery, so it is fast and lightweight. A DNS query is one small question retried by the application if needed, and a lost video frame is stale by the time it could be resent — so the guarantees TCP adds would be pure cost.

Q5. What is a socket?

  1. A synonym for a port number
  2. An IP address and port together
  3. The physical cable connecting two computers
  4. A firewall rule that blocks a port
Show answer

Answer: B. An IP address and port together

A socket is an IP-address-and-port pair (written host:port). A full connection is described by a four-tuple: source IP, source port, destination IP, destination port.

Q6. Which port range is reserved for well-known (system) services such as HTTPS on 443 and SSH on 22?

  1. 49152 – 65535
  2. 1024 – 49151
  3. 0 – 1023
  4. 8000 – 9000
Show answer

Answer: C. 0 – 1023

Ports 0–1023 are the well-known range for standard services. 1024–49151 are registered ports, and 49152–65535 are ephemeral ports the OS assigns temporarily to client programs.

Q7. You start a local server, point a client at it, and see "connection refused." What does that most precisely mean?

  1. The Internet connection is down
  2. The server requires a password that you did not provide
  3. The data was corrupted in transit
  4. The host was reached, but nothing is listening there
Show answer

Answer: D. The host was reached, but nothing is listening there

"Connection refused" means the network reached the host successfully and the host actively reported that no program is listening on the requested port — often a service that failed to start or is on a different port.

Q8. How does QUIC relate to TCP and UDP?

  1. A reliable transport built on UDP that underpins HTTP/3
  2. It replaces IP addresses with human-readable names
  3. It is an older protocol that TCP replaced
  4. It is a firewall that blocks unused ports
Show answer

Answer: A. A reliable transport built on UDP that underpins HTTP/3

QUIC (standardized as RFC 9000 in 2021) provides TCP-like reliability but runs over UDP, folding connection and encryption setup together to start sending data with fewer round-trips. It is the foundation of HTTP/3.

Glossary

port
A number from 0 to 65535 in a packet header that identifies which service or program on a host the data is for.
TCP
Transmission Control Protocol: a connection-oriented transport that guarantees data arrives complete, in order, by numbering bytes, acknowledging them, and retransmitting anything lost.
UDP
User Datagram Protocol: a connectionless, best-effort transport that sends packets with no handshake, ordering, or delivery guarantee — fast and low-overhead.
socket
One endpoint of a network connection, identified by an IP address and a port together (written host:port).
three-way handshake
The SYN, SYN-ACK, ACK exchange TCP performs before sending data, so both sides confirm they are ready and agree on starting sequence numbers.
packet
A small, individually addressed unit of data sent across a network; TCP and UDP wrap application data into packets carrying source and destination ports.
ephemeral port
A temporary high-numbered port (49152–65535) the operating system assigns to a client program for the outgoing side of a connection.
well-known port
A port in the range 0–1023 reserved for a standard service, such as 22 for SSH, 53 for DNS, 80 for HTTP, and 443 for HTTPS.
connection-oriented
Describing a protocol like TCP that establishes a connection (via a handshake) before exchanging data, and maintains state for it; UDP, by contrast, is connectionless.
QUIC
A modern transport protocol (RFC 9000, 2021) that provides TCP-like reliability on top of UDP with fewer setup round-trips, and is the foundation of HTTP/3.
listening
The state of a server socket that has claimed a port and is waiting for incoming connections addressed to it.
connection refused
The error returned when a host is reached but no program is listening on the requested port, so the connection cannot be completed.
flow control
A TCP mechanism where the receiver advertises how much data it can accept, so a fast sender does not overwhelm a slow receiver.
congestion control
A TCP mechanism that slows sending when the network shows signs of overload (lost packets or delay) and cautiously speeds back up, sharing capacity fairly.

Sources and further reading


Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.