Computing Foundations › How the Internet Works › Day 17
Day 17: 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.
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
- 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 - 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 - 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.
- 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:
- Explain what a port is (a 0–65535 number identifying a service on a host) and place any port in its IANA range: well-known (0–1023), registered (1024–49151), or ephemeral (49152–65535)
- Describe the TCP three-way handshake (SYN, SYN-ACK, ACK) step by step and state what each side communicates
- List TCP's four guarantees — reliability, ordering, flow control, and congestion control — and explain why the web depends on them
- Explain how UDP differs (connectionless, best-effort, low overhead) and name applications that prefer it: DNS, live media, games, and QUIC
- Define a socket as an IP-address-and-port pair and explain how a four-tuple identifies one connection
- Use lsof, ss/netstat, nc, and curl to inspect listening ports and test loopback connectivity, and interpret "connection refused"
- Connect the transport layer to model-serving practice: model servers listen on a port, and "connection refused" means nothing is listening there
Prerequisites
- Day 16 (IP Addresses, DNS, and Routing) — ports ride on top of the IP addressing you learned there
- Day 15 (What Happens When You Load a Web Page) for the end-to-end picture of a request
- A terminal on macOS, Linux, or WSL; no software to install beyond the standard OS tools
Why this matters
-
“Port already in use” is the error you will hit most this month, and today it becomes obvious rather than annoying.
-
Every model API call rides on TCP, and every timeout you debug is one of the guarantees in this lesson doing its job slowly.
-
Container networking is port mapping.
-p 8080:80is meaningless until you know what a port is. -
Firewalls think in ports. Reaching a training machine, or failing to, is usually one number.
-
The TCP-versus-UDP choice explains why video calls degrade and downloads do not.
The idea in plain language
-
An IP address gets you to the machine. A port gets you to the program.
-
A socket is the pair: an address and a port together identify one endpoint.
-
TCP is a phone call. Both sides agree to talk, everything arrives in order, and nothing is lost.
-
UDP is a postcard. It is sent, and it may or may not arrive, and nobody tells you.
-
Neither is better. They make opposite trades, and each is right for different work.
Historical background
-
The original 1974 design had one protocol doing addressing and reliability together.
-
It was split in 1978 into IP for addressing and TCP for reliability, which is why they are named as a pair and are two separate things.
-
UDP was added the same year for applications that wanted the addressing without the machinery.
-
The split was the good decision. It let IP stay simple enough to run over any medium, and let applications choose their own reliability.
-
Congestion control arrived in 1988, after congestion collapse nearly took the early internet down. TCP has slowed itself down voluntarily ever since.
-
QUIC, from 2012 onward, rebuilt TCP’s guarantees on top of UDP — which is only possible because UDP gave up so little.
What it is — and what it is not
-
A port is a 16-bit number in the header of every TCP and UDP packet — one for the source, one for the destination.
-
A socket is a program’s claim on a port, and the kernel delivers matching packets to it.
-
A connection is four numbers: source address, source port, destination address, destination port.
They are not:
-
Not physical. There is no socket on the back of the machine; it is a kernel data structure.
-
Not security. A port being closed is not protection; a firewall is.
-
Not tied to a protocol by law. Port 443 is HTTPS by convention, and anything may listen there.
-
Not unlimited. There are 65,535 of them, and a busy machine can genuinely run out of ephemeral ports.
Why it was created and what problems it solves
-
One machine, many services. Without ports, a computer could offer exactly one thing.
-
Delivery to the right program. The kernel needs to know which of a hundred processes a packet belongs to.
-
Reliable delivery over an unreliable network. IP may lose, duplicate and reorder; TCP hides all three.
-
Fairness. Congestion control is what stops a few fast senders from crowding everyone else out.
-
A choice. UDP exists so that applications which do not want those guarantees are not forced to pay for them.
How it works
Ports: one number per service
| Range | Name | Meaning | Examples |
|---|---|---|---|
| 0–1023 | Well-known | Standard services; usually need admin rights to open | 22 SSH, 53 DNS, 80 HTTP, 443 HTTPS |
| 1024–49151 | Registered | Assigned to applications on request | 3306 MySQL, 5432 PostgreSQL, 6379 Redis, 8080 alt-HTTP |
| 49152–65535 | Ephemeral | Temporary numbers the OS hands to clients | your browser’s outgoing side |
- Clients get a throwaway high port; servers listen on a fixed low one.
- That asymmetry is the shape of almost every connection you will ever make.
The socket: host plus port
-
“Listening on port 443” means the kernel has reserved that port and will deliver anything addressed there to that program.
-
A live connection is fully described by four numbers.
-
That four-tuple is why one server holds thousands of simultaneous connections on the same port. Each is a distinct combination.
TCP: the handshake
- SYN. “Can we talk? I will start counting from x.”
- SYN-ACK. “Yes, I heard you. I will start counting from y.”
- ACK. “Got it — let’s go.” The connection is established.
Once established, TCP delivers four guarantees:
-
Reliability. Every byte is numbered and acknowledged; anything unacknowledged after a timeout is retransmitted.
-
Ordering. Sequence numbers let the receiver reassemble bytes in the order sent, however scrambled they arrive.
-
Flow control. The receiver advertises how much buffer it has, so a fast sender cannot overwhelm a slow one.
-
Congestion control. TCP watches for loss and delay, slows down, then probes cautiously back up — the algorithm that quietly shares the internet’s capacity among millions of connections.
UDP: send and forget
-
No handshake. The first packet is the data.
-
No sequence numbers, no acknowledgements, no retransmission, no flow or congestion control.
-
A datagram carries source and destination ports, a length, a checksum, and the payload. That is all.
-
The receiver either gets it or does not, and UDP never tells the sender which.
-
That is exactly right for a name lookup, for live media where a lost frame is stale before you could resend it, and for anything that wants to build its own delivery rules on a lean foundation — which is what QUIC does.
An everyday analogy
An office building with a switchboard.
| The building | The network |
|---|---|
| The street address | The IP address |
| The extension number | The port |
| The switchboard | The kernel, routing to sockets |
| ”Extension 443, please” | Connecting to a service |
| A registered call, both parties confirmed | TCP |
| A note pushed under the door | UDP |
-
The address gets you to the building; the extension gets you to a person.
-
A phone call confirms both sides are present before anyone says anything important. That is the handshake.
-
A note under the door is faster and cheaper, and you will never know if it was read.
Examples in practice
-
Address already in use: another process holds that port.lsof -i :8080names it. -
A connection that hangs rather than refusing: a firewall dropping packets silently, rather than a machine answering “nothing here”.
-
Connection refused: the machine is reachable and nothing is listening. That is a useful error. -
A video call that degrades but continues: UDP, dropping frames rather than waiting for them.
-
A download that stalls and resumes: TCP retransmitting, invisibly, exactly as designed.
Implications: security, privacy, performance, scalability, and cost
-
Security: every open port is a way in. The first thing an attacker does is find out which ones answer.
-
Binding to
0.0.0.0exposes a service on every interface; binding to127.0.0.1exposes it only to the machine itself. That one choice is the difference between a local database and a public one. -
Privacy: ports leak what you run. A scan reveals your stack before anyone has read a line of your code.
-
Performance: the handshake costs a round trip, every new connection. Reuse connections and you stop paying it.
-
Scalability: ephemeral ports are finite. A machine making tens of thousands of short-lived outbound connections can exhaust them, which produces a confusing failure that looks like the network breaking.
-
Cost: congestion control means your throughput depends on loss. A slightly lossy path can halve your effective bandwidth while looking perfectly connected.
Alternatives: free, open source, and commercial
| Tool | Type | What it tells you |
|---|---|---|
lsof -i | Free, built in | Which process holds which port |
ss / netstat | Free, built in | Every socket, and its state |
nc (netcat) | Free, built in | Whether a port answers, and what it says |
nmap | Free, open source | Which ports are open on a host you own |
tcpdump | Free, built in | The packets themselves |
| Wireshark | Free, open source | The same, decoded and readable |
-
Learn
lsof -i :PORTtoday. It answers “what is on my port” in one line, and you will type it for the rest of your career. -
Only scan hosts you are authorised to scan.
nmapagainst someone else’s network is not a neutral act.
Comparison with related concepts
| Term | What it actually is |
|---|---|
| Port | A 16-bit number identifying a program on a host |
| Socket | A program’s bound endpoint: address plus port |
| Connection | The four-tuple of both addresses and both ports |
| TCP | Reliable, ordered, congestion-controlled byte stream |
| UDP | Unreliable, unordered datagrams with almost no machinery |
| QUIC | TCP-like guarantees rebuilt on top of UDP |
When to use it — and when not to
-
Use TCP when completeness matters more than timeliness — files, pages, API calls, anything where a missing byte is a broken result.
-
Use UDP when timeliness matters more than completeness — live audio and video, telemetry, game state, name lookups.
-
Use UDP when you want to build your own rules, as QUIC did.
-
Do not bind a development service to
0.0.0.0on a shared or public network without deciding to. -
Do not use a well-known port for your own service unless it is the service that port means.
-
Do not treat “the port is closed” as security. It is the absence of an opening, not the presence of a defence.
The AI connection
-
Every hosted model call is TCP, and a slow one is a round trip you can measure rather than a mystery.
-
Local inference servers bind a port — Ollama, vLLM, a notebook — and two of them wanting the same number is the most common local failure.
-
Container port mapping is this lesson:
-p 8080:80says “the host’s 8080 reaches the container’s 80”, and nothing more mysterious. -
Distributed training coordinates over TCP on ports you configure, which is why a firewall between nodes stops a run before it starts.
-
Streaming token responses hold one connection open rather than making many, which is the round-trip argument from Day 15 applied.
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
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 doing | Command |
|---|---|
| See every listening socket | ss -tlnp or lsof -iTCP -sTCP:LISTEN |
| Find what holds one port | lsof -i :8080 |
| Start a server on a port | python3 -m http.server 8080 |
| Connect to it | curl http://127.0.0.1:8080/ |
| Check a port without a client | nc -vz 127.0.0.1 8080 |
| Watch the handshake | sudo tcpdump -i lo0 -c 6 port 8080 |
| Cause the classic error | Start 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
(LISTEN)is a socket waiting for connections.Address already in useis the port already claimed — the error this lesson exists to make obvious.
Validate your work
- You listed the listening sockets on your machine and recognised three services
- You started a server and connected to it from another terminal
- You reproduced “address already in use” deliberately
- You saw the difference between a refused connection and a dropped one
- You can state the four numbers that identify a connection
-
bash tests/run_tests.shreports 0 failures
Troubleshooting
-
lsofshows nothing withoutsudo. You can only see your own processes; other users’ sockets need elevation. -
Permission deniedbinding to port 80. Ports below 1024 need administrator rights. Use 8080. -
The port stays busy after you stop the server. TCP holds it briefly in
TIME_WAITso late packets cannot confuse a new connection. Wait, or use a different port. -
ncnot found.curl -von the address will tell you the same thing.
Common mistakes
-
Assuming a closed port means a broken service. Check which address it bound to first.
-
Binding to
127.0.0.1and expecting another machine to reach it. -
Reading “connection refused” as a firewall. It is the opposite — something answered.
-
Scanning networks you do not own.
Practice assignment
-
Inventory every listening port on your machine and identify the program behind each. Anything you cannot explain is worth ten minutes.
-
Bind the same server to
127.0.0.1and then to0.0.0.0, and try reaching it from a phone on the same network. The difference is the lesson. -
Capture a handshake with
tcpdumpand label the SYN, SYN-ACK and ACK by hand. -
Compare a TCP and a UDP transfer of the same data on a lossy link, using
tc netemor simply a poor Wi-Fi connection.
Extension challenge
-
Exhaust the ephemeral port range deliberately with a script making thousands of short-lived connections, and observe the failure. It looks nothing like “out of ports”, which is why it is worth seeing once.
-
Watch congestion control work. Transfer a large file while running a second transfer, and watch each one’s throughput adjust.
-
Write a minimal TCP echo server and a UDP one in twenty lines each, and note precisely which lines the UDP version does not need.
-
Read a QUIC handshake capture and identify what it folded together that TCP and TLS keep separate.
Quiz
Q1. What does a port number identify?
- A physical socket on the back of the computer
- A specific service on a host, so one machine can run many
- The physical route a packet takes across the Internet
- 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?
- ACK, SYN, SYN-ACK
- SYN, ACK, SYN-ACK
- SYN, SYN-ACK, ACK
- 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?
- Encryption of the data payload end to end
- Faster delivery with no connection setup cost
- Hiding which IP addresses are communicating
- 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?
- It is connectionless and low-overhead, and they tolerate loss
- Because it guarantees every packet arrives in order
- Because it encrypts each packet automatically
- 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?
- A synonym for a port number
- An IP address and port together
- The physical cable connecting two computers
- 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?
- 49152 – 65535
- 1024 – 49151
- 0 – 1023
- 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?
- The Internet connection is down
- The server requires a password that you did not provide
- The data was corrupted in transit
- 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?
- A reliable transport built on UDP that underpins HTTP/3
- It replaces IP addresses with human-readable names
- It is an older protocol that TCP replaced
- 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
- Transmission Control Protocol — Wikipedia (accessed 2026-07-12)
- User Datagram Protocol — Wikipedia (accessed 2026-07-12)
- Port (computer networking) — Wikipedia (accessed 2026-07-12)
- High Performance Browser Networking — Building Blocks of TCP — Ilya Grigorik (accessed 2026-07-12)
- What is TCP/IP? — Cloudflare (accessed 2026-07-12)
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.