Linux Networking from Zero
Tested 2026-11-27 on Ubuntu 22.04.4 LTS host (Linux 6.8), 4-core Arm Neoverse-N1 (aarch64), 23 GB RAM; Docker Engine 29.1.3 · with Ubuntu 26.04.1 LTS (ubuntu:26.04 image), iproute2 6.19.0, iptables 1.8.11 (nf_tables), nftables 1.1.6, tcpdump 4.99.6, curl 8.18.0, Docker Engine 29.1.3 · by the fromzero project · CC BY 4.0
Your app calls another service, and all you get back is one line: Could not connect to server.
That same line comes from at least three different problems. Nothing is listening, there’s no route, or nobody on the network has that address. The only visible difference is how long it took: 0 ms, 0 ms or 3 seconds.
So people guess: restart the container, open the firewall, blame DNS. But every connection asks the same six questions in the same order.
Ask them one by one with the right Linux tool, and the first “no” is your problem.
This course builds networks with you from zero, inside one container on your own computer: namespaces as machines, virtual cables, a router, a switch, a firewall. You build each piece yourself, so you know what each tool’s output means and what breaks when it’s missing.
By the end you’ll be able to:
- read a machine’s interfaces, addresses, routes, neighbours and listening sockets, and say what each one means for a connection;
- connect isolated “machines” with virtual cables, a bridge and a router, the way Docker does;
- tell “refused”, “unreachable”, “no route to host” and “timed out” apart, and know which part of the system each points to;
- write firewall and NAT rules that let in only what you mean;
- trace “it can’t connect” step by step with a script you wrote yourself, and say where it breaks.
How it works
Each lesson starts from zero with an animated, step-by-step picture (press Play, or step with the arrow
keys), then explains in plain words, with optional Go deeper sections. Each practical has you build the
network yourself, with requirements, a hint, a hidden solution, a “predict first” question and a part where you
break it on purpose. One script, ./lab, checks your work:
./lab setup pNgets what a practical needs that isn’t its topic (in Practical 0, just a check that Docker runs)../lab check pNtells you whether your lab is right. Checks only read, except p3’s: it breaks your lab on purpose, one way at a time, and undoes each break../lab reset pNrebuilds the lab as the earlier practicals left it, when an experiment went too far.
All you need is Docker Engine on your Linux server, and a few hundred MB of disk. Everything runs inside one lab container that you start yourself.
Path
| Lesson | Practical | You’ll be able to |
|---|---|---|
| 1 · What happens when you connect | name the six questions every connection asks, and match an error to one | |
| 2 · The Linux network stack | 0 · Your lab: two namespaces and a cable | read the five tables; build two machines and a cable; diagnose an unplugged cable |
| 3 · IP addresses and subnets | say which addresses are on your link and which need a router | |
| 4 · Routing | 1 · A router between two networks | route between networks, and trace a missing route |
| 5 · ARP and bridges | see how a frame finds a machine on a link; build a switch | |
| 6 · Ports, sockets and TCP | 2 · A switch and a service | watch the handshake; tell refused from timed out |
| 7 · Firewalls and NAT | drop, reject, masquerade and forward ports with iptables and nft | |
| 8 · What really happens when you run curl | 3 · Capstone: netcheck | trace a connection end to end; write a script that names the broken step |
What your folder will look like
~/linux-networking-zero/ on your computer, and at the same path inside netlab
├── lab the lab script: ./lab setup|check|reset pN
├── lab.log every command ./lab ran, with its output
├── on your 5-line script: ./on opens a shell in netlab (Practical 0)
├── p0.sh rebuilds red and blue after a restart (Practical 0)
├── ... one script per practical: p1.sh, p2.sh, p3.sh
└── netcheck/ your capstone: the netcheck script (Practical 3)
1 · What happens when you connect
In one sentence: a connection is a short chain of questions (which address, which way, who on the link, allowed through, anyone listening, any answer), and every “it can’t connect” is one of them answered “no”.
The problem it solves
Your program calls http://web:8080/ and gets an error. Here is the same curl command failing five times, each
time for a different reason, on two “machines” joined by a virtual cable (the lab you’ll build in Practical 0, plus
the breakages that lessons 3 to 8 teach):
| What was wrong | curl -sS prints | after | curl -v adds | Question (lesson) |
|---|---|---|---|---|
no machine is called web | curl: (6) Could not resolve host: web | under a second | (no address to try) | 1 (8) |
| this machine has no way to 10.0.0.2 | curl: (7) Failed to connect to 10.0.0.2 port 8080 after 0 ms: Could not connect to server | 0 ms | Network is unreachable | 2 (3, 4) |
| no machine on the link has the address | curl: (7) Failed to connect to 10.0.0.9 port 8080 after 3076 ms: Could not connect to server | 3 s | No route to host | 3 (5) |
| a firewall throws the packets away | curl: (28) Connection timed out after 5002 milliseconds | 5 s | (nothing came back) | 4 (7) |
| no program listens on port 8080 | curl: (7) Failed to connect to 10.0.0.2 port 8080 after 0 ms: Could not connect to server | 0 ms | Connection refused | 5 (6) |
Three different problems print the same sentence. Guessing from it (“must be the firewall”) turns an outage into an afternoon. Knowing what happens, in what order, when a connection is made lets you check each step instead.
The idea: six questions in order
Think of posting a parcel to a friend in a big apartment building.
- Name → address. You know “Sam”; the courier needs a street address. Computers know names like
webbut send to numbers, IP addresses such as10.0.0.2. Looking a name up is DNS (or the file/etc/hosts). - Which way? Is the address on your street, or does the parcel go via the depot? The routing table answers for each address: which interface (network card) to use, and through which machine.
- Which door? On your street, which house is it? On a network link, “who has 10.0.0.2?” is answered by ARP: the owner replies with its MAC address, the hardware address of its network card.
- Let through? A guard at the gate may refuse parcels. A firewall may drop packets or reject them.
- Which flat? A building has many flats; a machine has many programs. The port number (8080) says which one. A program has to be listening on it.
- Does someone answer? The program reads the request and replies. That’s the application, HTTP here.
Data travels as packets: small chunks, each with the sender’s and receiver’s addresses on the front.
What it looks like on the wire
tcpdump prints every packet that crosses an interface. Here is the one successful curl from red (10.0.0.1) to
the server on blue (10.0.0.2), seen on blue’s end of the cable, long lines cut:
14:06:16.256706 ARP, Request who-has 10.0.0.2 tell 10.0.0.1, length 28
14:06:16.256718 ARP, Reply 10.0.0.2 is-at 1a:b5:b8:0f:df:2d, length 28
14:06:16.256726 IP 10.0.0.1.47446 > 10.0.0.2.8080: Flags [S], seq 1246910117, win 64240, ...
14:06:16.256739 IP 10.0.0.2.8080 > 10.0.0.1.47446: Flags [S.], seq 2919238786, ack 1246910118, ...
14:06:16.256751 IP 10.0.0.1.47446 > 10.0.0.2.8080: Flags [.], ack 1, win 502, ...
14:06:16.256811 IP 10.0.0.1.47446 > 10.0.0.2.8080: Flags [P.], seq 1:78, ack 1, ... length 77: HTTP: GET / HTTP/1.1
...
14:06:16.256824 IP 10.0.0.2.8080 > 10.0.0.1.47446: Flags [P.], seq 1:64, ack 78, ... length 63: HTTP: HTTP/1.1 200 OK
...
14:06:16.256861 IP 10.0.0.2.8080 > 10.0.0.1.47446: Flags [F.], seq 64, ack 78, ...
Top to bottom, the questions are answered in order. The name was already an address. Two ARP
packets find blue’s MAC. Then the TCP handshake: [S] (SYN, “can we talk?”), [S.] (SYN-ACK, “yes”),
[.] (ACK, “good”). Then the request, the answer, and [F.] (FIN) to close. It took 0.2 milliseconds.
Each failure in the table at the top stops at one of these questions (its last column). The plain message hides
the difference; the time and curl -v (which prints each step curl takes) show it.
Layers
The six questions are usually drawn as layers, each built on the one below:
application HTTP, DNS question 6 (and 1: DNS is an application too)
transport TCP, UDP: ports question 5
network IP: addresses, questions 2 and 4
routes, firewall
link Ethernet: MAC, ARP question 3
When you debug, ask the questions in order: each depends on the ones before it, so there’s no point checking the port while there’s no route. The capstone of this course is a script that does exactly that.
Try it on your computer
Practical 0, after lesson 2, has you build the two machines, red and blue, and the cable these outputs
came from. The later practicals add the router, the switch and the firewall.
Go deeper: why the timings differ
- 0 ms, refused. Blue’s kernel (the core of Linux, which does all the networking) got the SYN, found nothing listening on 8080, and answered with a TCP reset
(
Flags [R.]in tcpdump) 13 microseconds later. - 0 ms, unreachable. Red’s own routing table had no route, so the kernel refused before sending anything.
- About 3 s, no route to host. Red sent 3 ARP requests for 10.0.0.9, about 1 s apart, and nobody answered.
The kernel then marked the neighbour
FAILED(ip neighshows10.0.0.9 dev veth-red FAILED) and told curlNo route to host. The 3 and the 1 s are the settingsmcast_solicit = 3andretrans_time_ms = 1000on red’s end of the cable (ip-sysctl, neighbour section). - 5 s, timed out. The firewall dropped the SYN silently, and red’s kernel kept resending it. curl stopped at
the
--max-time 5it was given. Without a limit, on this machine’s kernel, red resent the SYN 10 times (the last 68 s after the first), and curl gave up after 134 s. The settings behind it aretcp_syn_retriesandtcp_syn_linear_timeouts(same page, TCP section).
So fast means someone said no; slow means nobody said anything.
Common misunderstandings
- “Connection refused means a firewall.” Refused means a machine answered “nothing listens there”. The network worked. A firewall that drops shows up as a timeout instead (lesson 7 shows the REJECT case).
- “
pingworks, so the service is fine.” Ping tests questions 2–4 with a different protocol (ICMP, the protocol ping uses, with no ports). It says nothing about the port or the program.
Check yourself
1. curl fails "after 0 ms" with Could not connect to server. Which two questions could it be, and how do you tell?
Route (2) or port (5): both are immediate. curl -v says Network is unreachable for a missing
route, Connection refused for no listener.
2. A request hangs for exactly as long as your client's timeout. Which question is the likeliest suspect, and why not "nobody listening"?
A firewall dropping packets (4): nothing comes back, so the client waits. If nobody were listening, the other machine would answer "refused" at once.3. A colleague has a web server that answers ping but not curl. Which questions has ping already answered "yes"?
Route, neighbour, and that the firewall lets ICMP through: 2, 3 and part of 4. Still open: whether the firewall lets
TCP to that port through, whether anything listens on it, and whether it answers.
Next: lesson 2 · The Linux network stack.
2 · The Linux network stack
In one sentence: Linux keeps networking in five tables (interfaces, addresses, routes, neighbours, sockets); a network namespace is a separate, empty copy of all five, and a veth pair is a cable between two of them.
The problem it solves
Lesson 1 split a connection into questions: which address, which way out, who on the link, is anyone listening. To check each one you need to know where Linux keeps the answer. And to practise breaking networks you need several machines you can wreck in seconds, without touching your own computer’s network.
Both have the same answer. The kernel’s networking lives in a few tables you can read with ip and ss, and Linux
can make as many independent copies of those tables as you like.
Five tables
Here is the lab container you’ll build in Practical 0, read table by table. -br asks ip for its brief, one line
per item form.
Interfaces (ip -br link): the places packets go in and out. A real network card, a virtual one, or lo, the
loopback, which is the machine talking to itself.
lo UNKNOWN 00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP>
eth0@if822 UP a2:f4:40:4f:79:35 <BROADCAST,MULTICAST,UP,LOWER_UP>
The columns are name, state and MAC address, the interface’s hardware address used on its own link. The flags in
<...> follow. UP means you switched it on. LOWER_UP means the other side is there too, like a cable plugged in
at both ends.
Addresses (ip -br addr): the IP addresses each interface answers to.
lo UNKNOWN 127.0.0.1/8 ::1/128
eth0@if822 UP 172.17.0.3/16
The /16 after the address says how big the local network is (lesson 3 takes it apart).
Routes (ip route): for each destination, which interface to send it out of, and through which machine.
default via 172.17.0.1 dev eth0
172.17.0.0/16 dev eth0 proto kernel scope link src 172.17.0.3
The second line says that anything in 172.17.x.x is on eth0’s link, so it goes straight there. Nobody typed it:
proto kernel means the kernel added it when the address was added. The first line, default, catches everything
else and hands it to 172.17.0.1, the gateway, a machine that forwards packets onwards.
Neighbours (ip neigh): the MAC addresses of machines on the same link that this one has talked to. After one
ping to the gateway:
172.17.0.1 dev eth0 lladdr ea:92:21:b2:12:84 REACHABLE
Sockets (ss -tln): programs waiting for TCP connections (-t TCP, -l listening, -n numbers, not names).
Nothing listens in a fresh container, so it prints only its header:
State Recv-Q Send-Q Local Address:Port Peer Address:Port
| Table | Answers | Read it with |
|---|---|---|
| interfaces | is the cable there and switched on? | ip link |
| addresses | which addresses are mine? | ip addr |
| routes | which way to that address? | ip route |
| neighbours | which MAC has that address on my link? | ip neigh |
| sockets | is a program listening on that port? | ss -tln |
A namespace: a whole new set of tables
ip netns add red creates a network namespace called red. It is a second network stack inside the same
kernel, with its own five tables, and it starts almost empty. ip -n red <command> runs an ip command in it;
ip netns exec red <program> runs any program there.
ip netns add red
ip -n red link
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN mode DEFAULT group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
Only a loopback, and it’s DOWN. No addresses, no routes (ip -n red route prints nothing), no sockets. Even
talking to itself fails:
ip netns exec red ping -c1 127.0.0.1
ping: connect: Network is unreachable
That message means the stack has no route for the address. With lo down, 127.0.0.1 isn’t anywhere.
ip -n red link set lo up fixes it.
A program started in a namespace sees only that namespace’s tables. A server listening on port 8080 in blue shows
up in ip netns exec blue ss -tln and nowhere else. That is what makes a namespace behave like a separate
machine, and it is exactly how Docker gives each container its own network.
A veth pair: a cable
A veth pair (virtual Ethernet) is two interfaces created together. A packet sent into one comes out of the other. Create the pair, then move each end into a namespace:
ip link add veth-red type veth peer name veth-blue
ip link set veth-red netns red
ip link set veth-blue netns blue
Before the move, ip -br link in the container shows both ends, each naming its partner after the @. After it,
they’re gone from the container and appear in red and blue. Add an address on each end
(ip -n red addr add 10.0.0.1/24 dev veth-red, and 10.0.0.2/24 in blue). A cable still needs both ends
switched on. With only red’s end up:
lo UNKNOWN 00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP>
veth-red@if3 LOWERLAYERDOWN 92:21:d1:d5:48:61 <NO-CARRIER,BROADCAST,MULTICAST,UP>
Red’s end is UP, but there’s NO-CARRIER: nothing alive on the other end. Red’s route is there, marked linkdown,
and a ping just gets no answer:
10.0.0.0/24 dev veth-red proto kernel scope link src 10.0.0.1 linkdown
Bring blue’s end up too, and red can reach blue:
64 bytes from 10.0.0.2: icmp_seq=1 ttl=64 time=0.029 ms
64 bytes from 10.0.0.2: icmp_seq=2 ttl=64 time=0.034 ms
64 bytes from 10.0.0.2: icmp_seq=3 ttl=64 time=0.037 ms
Red’s neighbour table now holds blue’s MAC, the same a2:ee:74:23:6c:42 that ip -n blue link shows for
veth-blue:
10.0.0.2 dev veth-red lladdr a2:ee:74:23:6c:42 REACHABLE
Try it on your computer
Practical 0 · Your lab: two namespaces and a cable: build the lab
container, make red and blue, join them with a veth pair and ping across it. Then unplug it on purpose and read
what each table says.
Go deeper: what a namespace is, and where it lives
The kernel has several kinds of namespace: network, mount, process IDs, users and others. Each gives a process its
own view of one resource. A container is a process with several of them at once. A network namespace holds its own
interfaces, routing tables, neighbour tables, firewall rules, sockets and its own net.* settings under
/proc/sys/net (network_namespaces(7)).
ip netns add names a namespace by bind-mounting it to a file in /run/netns/. While that mount, or any process
in the namespace, exists, the namespace stays alive
(ip-netns(8)). Restart the lab container and the mounts are
gone, but the files remain. ip netns list then prints red and blue after four lines of
Error: Peer netns reference is invalid., and entering one fails:
setting the network namespace "red" failed: Invalid argument
So namespaces don’t survive a restart. Practical 0 has you put the setup in a script for that reason.
Go deeper: the veth pair is one object
The two ends of a veth pair belong together: delete either end and the kernel deletes both. After
ip -n blue link del veth-blue, ip -n red -br link shows only lo, and red’s 10.0.0.0/24 route goes with it.
The @if3 after veth-red is the index of its partner interface, which lives in another namespace, so ip can’t
show its name. ip -n red link show veth-red names that namespace: link-netns blue.
Docker uses the same pieces. Each container gets a namespace and one end of a veth pair; @if822 in the
container’s eth0@if822 is the interface number of the other end, which stays on the host. For a lab container
whose eth0 said @if841, the host’s interface 841 was:
841: veth038851b@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP mode DEFAULT ...
That is a veth end, plugged (master docker0) into Docker’s bridge, a virtual switch that lesson 5 builds by hand.
Common misunderstandings
- “A namespace is a container.” A container uses a network namespace, plus others for files and processes. A bare network namespace shares the container’s files and programs; only the network is separate.
- “
UPmeans it works.”UPmeans you switched your end on.LOWER_UP(or noNO-CARRIER) means the other end is there too. Read both. - “I have to add the route for my own network.” Adding
10.0.0.1/24on an interface that’s up adds the10.0.0.0/24route by itself (proto kernel). You add routes only for networks you reach through another machine (lesson 4).
Check yourself
1. In a brand-new namespace, ping 127.0.0.1 says Network is unreachable. Which table, and what fixes it?
The routes: with lo down, the stack has no route for 127.0.0.1. ip -n <ns> link set lo up
brings it up, and loopback addresses work.
2. ip -n red -br link shows veth-red as LOWERLAYERDOWN with NO-CARRIER. What do you check next?
The other end of the cable. Red's end is up, but its partner isn't: look in the namespace that holds it
(ip -n blue -br link) and bring it up.
3. A server listens on port 8080 in blue. You run ss -tln in the container and don't see it. Is the server down?
Not necessarily: ss shows the sockets of the namespace it runs in. Run
ip netns exec blue ss -tln to see blue's.
Next: Practical 0 · Your lab, then lesson 3 · IP addresses and subnets.
3 · IP addresses and subnets
In one sentence: the
/24after an address says how many of its first bits name the network; every address in that network is on the link and reached directly, and every other address needs a router.
The problem it solves
In Practical 0 you gave red 10.0.0.1/24 and blue 10.0.0.2/24, and they could talk. Now keep the same cable
and give blue 10.0.1.2/24 instead. Red’s ping fails before a single packet leaves:
ping: connect: Network is unreachable
The cable is fine, both ends are up. What changed is one number in the address, and the /24 decides whether that
number matters. Misread prefixes cause some of the most confusing failures there are: “it’s plugged in, it pings
one way, but not the other”.
The idea: a street and a house number
An IPv4 address is 32 bits, written as four numbers from 0 to 255 (10.0.0.1). The prefix length, the number
after the /, splits it in two:
- the first part,
/24bits long, is the network: the street; - the rest names one machine on it: the house number.
10 . 0 . 0 . 1 /24
[------ network ------][host]
10.0.0.x : 256 addresses on this network
10 . 0 . 0 . 1 /16
[-- network --][-- host ---]
10.0.x.x : 65,536 addresses on this network
Two addresses are on the same network when their network parts are equal. 10.0.1.2 is in 10.0.0.0/16
(10.0 matches) but not in 10.0.0.0/24 (10.0.0 doesn’t).
| Prefix | Network part | Addresses | Typical use |
|---|---|---|---|
/8 | 10.x.x.x | 16,777,216 | a whole private range |
/16 | 172.17.x.x | 65,536 | Docker’s default network |
/24 | 10.0.0.x | 256 | a home or office network |
/30 | 4 addresses | 4 | a link between two routers |
/32 | the whole address | 1 | one address only |
On the link, or through a router
When you add 10.0.0.1/24 to an interface, the kernel adds a route for the whole network, with the host part set
to zero:
10.0.0.0/24 dev veth-red proto kernel scope link src 10.0.0.1
scope link is the point: every address in 10.0.0.0/24 is on this link, so the kernel sends to it directly.
It doesn’t check that anyone is there. Ask about an address nobody has:
ip -n red route get 10.0.0.77
10.0.0.77 dev veth-red src 10.0.0.1 uid 0
An address outside every network you’re on needs a router, a machine that passes packets between networks
(lesson 4). Red has no route at all for 10.0.1.2, which is what Network is unreachable means: no packet is sent,
the error comes from red’s own routing table.
Change both prefixes to /16 on the same cable, and red’s route becomes 10.0.0.0/16. Now 10.0.1.2 is on the
link and the ping works:
3 packets transmitted, 3 received, 0% packet loss, time 2078ms
Both sides have to agree
Now give red /16 and leave blue at /24. Red thinks blue is on its link; blue thinks red isn’t on its own. Red
pings: 100% packet loss. tcpdump in blue shows red asking for blue’s hardware address (an ARP request,
lesson 5), three times, a second apart, and never getting an answer:
15:42:49.085989 ARP, Request who-has 10.0.1.2 tell 10.0.0.1, length 28
15:42:50.107065 ARP, Request who-has 10.0.1.2 tell 10.0.0.1, length 28
15:42:51.131062 ARP, Request who-has 10.0.1.2 tell 10.0.0.1, length 28
Blue doesn’t answer because it has no route to 10.0.0.1, and its kernel checks that before it replies:
reverse-path filtering, rp_filter, here 2 (“drop what I couldn’t answer by any route”). A new namespace
copies that setting from your computer’s own network settings. With rp_filter at 0, blue answers the ARP and
only the ping replies are lost: blue has no way to send them.
Give blue a route (ip -n blue route add 10.0.0.0/16 dev veth-blue) and it answers the ARP at once and all three
pings come back.
A conversation needs a route in both directions, and with wrong prefixes one side may never even reply to “who
are you?”.
Try it on your computer
Lesson 4 adds the router, and Practical 1 builds it. In your Practical 0 lab you can already ask the kernel about any address without changing anything:
ip -n red route get 10.0.0.200
ip -n red route get 10.0.1.2
The first is on red’s link; the second is Network is unreachable.
Go deeper: the bits, the mask and the two reserved addresses
10.0.0.1 is 00001010.00000000.00000000.00000001 in binary. A /24 means the first 24 bits are the network.
Older tools write the same thing as a netmask, 24 ones then zeros: 255.255.255.0 (/16 is 255.255.0.0).
An address is in the network when address AND mask equals the network address
(RFC 950).
The kernel builds the route from the address with the host bits cleared: add 10.0.7.77/24 and the route is
10.0.7.0/24. In each network the first address (host bits all 0) names the network and the last (all 1) is the
broadcast address, so a /24 has 256 addresses and 254 for machines
(RFC 919).
A /32 is a network of one: add 10.0.5.1/32 to red and the address appears in ip -br addr, but no new route
does. Nothing else is on that “link”.
Go deeper: private ranges, and Docker's /16
Three ranges are set aside for private networks and never routed on the internet: 10.0.0.0/8, 172.16.0.0/12 and
192.168.0.0/16 (RFC 1918). Every address in this course is in one of
them. Docker’s default network is one too; read it on your server (read-only):
docker network inspect bridge --format '{{json .IPAM.Config}}'
[{"Subnet":"172.17.0.0/16","IPRange":"","Gateway":"172.17.0.1"}]
That’s why your lab container’s eth0 has a 172.17.x.x/16 address and a route 172.17.0.0/16 dev eth0: every
container on that network is on its link, and anything else goes to the gateway 172.17.0.1.
Common misunderstandings
- “Same cable, so they can talk.” The cable only carries frames. Each side decides from its own routes
whether the other is on its link; with
10.0.0.1/24and10.0.1.2/24, red won’t even try. - “The prefix is just part of the address.” It is a claim about the network. Both ends must make the same claim, or one of them won’t answer.
- “
10.0.0.0/24in the route table is a machine.” It’s the network: the host part is zero. The route covers all 256 addresses.
Check yourself
1. A machine has 192.168.1.10/24. Which of 192.168.1.200, 192.168.2.10 and 192.168.1.255 does it send to directly?
192.168.1.200 (same first three numbers). 192.168.1.255 is on the link too, but it's the network's broadcast
address. 192.168.2.10 is another network: it needs a route through a router.
2. Red pings an address and gets Network is unreachable instantly. Did a packet leave red?
No. The error comes from red's own routing table: no route matches. ip route get <address> says
the same thing without pinging.
3. Red (/16) pings blue (/24) on the same cable and gets no reply. tcpdump in blue shows ARP requests from red. What's missing?
Blue's way back: blue has no route to red's address, so it doesn't answer. Make the prefixes match (or give blue
a route).
Next: lesson 4 · Routing, then Practical 1 · A router between two networks.
4 · Routing
In one sentence: a route says “for these addresses, send out this interface, through this machine”; the kernel picks the most specific route that matches, a router passes packets from one of its links to another, and the reply needs a route back.
The problem it solves
Lesson 3 ended with two machines on different networks and ping: connect: Network is unreachable. Real networks
are always like that: your laptop is on 192.168.1.x, the server you want is on some other network far away, and
nothing connects them directly. Something in the middle has to pass packets along, and every machine has to know
where to hand them.
The idea: deliver it yourself, or hand it to the post office
A letter for your own street you carry over yourself. Anything else goes in the post box, and the post office works out the next step. A machine does the same:
- the address is on one of my links (a connected route,
proto kernel, from lesson 3): send it straight there; - otherwise, find a route that names a gateway, a machine on my link that will pass it on, and hand it to that.
The lab for this lesson has three namespaces. router has a leg in each network:
red router blue
veth-red 10.0.1.2/24 --- r-red 10.0.1.1/24
r-blue 10.0.2.1/24 --- veth-blue 10.0.2.2/24
network 10.0.1.0/24 network 10.0.2.0/24
Reading a routing table
With only the addresses set, red knows one network, its own:
10.0.1.0/24 dev veth-red proto kernel scope link src 10.0.1.2
So red can ping 10.0.1.1 (on its link) but not 10.0.2.2. ip route get <address> asks the kernel which route it
would use, without sending anything. For 10.0.2.2 it has none:
RTNETLINK answers: Network is unreachable
The router itself needs nothing extra: both networks are on its own links.
10.0.1.0/24 dev r-red proto kernel scope link src 10.0.1.1
10.0.2.0/24 dev r-blue proto kernel scope link src 10.0.2.1
Give red a default route, the “anything else” line, through the router:
ip -n red route add default via 10.0.1.1
ip -n red route get 10.0.2.2
10.0.2.2 via 10.0.1.1 dev veth-red src 10.0.1.2 uid 0
Read it as: to reach 10.0.2.2, send out veth-red to the gateway 10.0.1.1, with 10.0.1.2 as the sender
address. Blue gets the mirror image, default via 10.0.2.1.
A router has to agree to forward
A machine that receives a packet for someone else’s address normally throws it away. Passing it on is IP
forwarding, a setting called net.ipv4.ip_forward. Turn it off in the router and ping again:
ip netns exec router sysctl -w net.ipv4.ip_forward=0
ip netns exec red ping -c3 -W1 10.0.2.2
3 packets transmitted, 0 received, 100% packet loss, time 2046ms
tcpdump on the router’s red side shows the three requests arriving; on its blue side it captures nothing. The
router dropped them and sent no error back, so red only sees silence. Turn it on (=1) and the replies come:
64 bytes from 10.0.2.2: icmp_seq=1 ttl=63 time=0.055 ms
Look at ttl=63. Every packet carries a TTL (time to live), a counter each router lowers by one, so a packet
caught in a loop dies instead of circling forever. Blue sent its reply with 64; one router on the way made it 63.
A ping straight to the router comes back with ttl=64. Send a ping with its TTL set to 1 (-t1): it dies at the first
router, and that router tells you:
From 10.0.1.1 icmp_seq=1 Time to live exceeded
The way back
A connection is two one-way trips. Delete blue’s default route and ping from red again: 100% packet loss. Red’s
route is fine and the router forwards; tcpdump in blue shows all three echo requests arriving. But blue has no
route to 10.0.1.2, so it can’t send the replies. Ask blue’s kernel:
ip -n blue route get 10.0.1.2
RTNETLINK answers: Network is unreachable
When packets go out and nothing comes back, check the route back too, from the other machine.
Which route wins
When several routes match, the longest prefix wins: the most specific one. default is 0.0.0.0/0, prefix
length 0, so it matches everything and loses to anything else. Add a (wrong) route for half of blue’s network:
ip -n red route add 10.0.2.128/25 dev veth-red
Now 10.0.2.200 is in the /25, so the kernel sends it straight out of veth-red, no gateway, while 10.0.2.2
still goes through the router:
10.0.2.200 dev veth-red src 10.0.1.2 uid 0
10.0.2.2 via 10.0.1.1 dev veth-red src 10.0.1.2 uid 0
That’s how one wrong route breaks a few addresses and leaves the rest working. ip route get shows which route
wins for any address. One more rule: the gateway must be on a link you have. ip -n red route add 10.0.9.0/24 via 10.0.2.1 fails with Error: Nexthop has invalid gateway.
| Symptom from red | First table to read | Where |
|---|---|---|
Network is unreachable at once | routes: no route matches | red: ip route get |
| silence, nothing comes back | forwarding, then the route back | router: sysctl net.ipv4.ip_forward; blue: ip route |
Time to live exceeded from a router | the packet’s TTL ran out there | (a loop, or -t set low) |
Try it on your computer
Practical 1 · A router between two networks: build red, router and blue, route between them, switch forwarding off and on, then delete a route back and find it.
Go deeper: how the kernel picks a route
For each packet the kernel looks up the destination in the routing table and takes the matching route with the
longest prefix; among routes of the same prefix, the lowest metric. The answer is the outgoing interface, the
gateway (if any) and the source address (src). ip route get runs the same lookup and prints it.
A route with via sends the packet to the gateway’s MAC address (found with ARP, lesson 5) while the IP
header still says 10.0.2.2: the IP address is where it’s going, the MAC is the next hop. That’s why the gateway
must be on one of your links. More in ip-route(8).
Every namespace has its own table. The lab container’s, with Docker’s gateway:
default via 172.17.0.1 dev eth0
172.17.0.0/16 dev eth0 proto kernel scope link src 172.17.0.4
Go deeper: ip_forward belongs to the namespace
net.ipv4.ip_forward is one of the per-namespace net.* settings (lesson 2). In the lab it is already 1 in the
container, and red and router were 1 too before anything was changed. Setting it to 0 in router leaves the
container’s at 1.
Where the 1 comes from: a new namespace copies its IPv4 settings from your computer’s own, and Docker Engine
turned forwarding on there. So in the lab, forwarding is on unless you switch it off; Practical 1 switches it off
first to see the difference, and sets it back with sysctl -w.
A machine with forwarding on and more than one network is a router, whether you meant it or not. On a server,
sysctl net.ipv4.ip_forward says which it is. The kernel’s own description of the setting is in
ip-sysctl.
Common misunderstandings
- “The router needs a default route.” Not to join two networks it sits on: both are connected routes. It needs one only to reach networks beyond.
- “No reply means my side is wrong.” Requests can arrive perfectly and the reply be lost: no route back, or
forwarding off on the way.
tcpdumpon the far side tells you which half failed. - “A gateway is an address far away.” A gateway is always on one of your links: the next machine, not the destination.
Check yourself
1. Red's ping to 10.0.2.2 gets 100% packet loss and no error. tcpdump on router's r-red sees the requests, on r-blue nothing. What do you check?
The router isn't passing them on: ip netns exec router sysctl net.ipv4.ip_forward. It says 0;
set it to 1.
2. The replies from a machine say ttl=62. How many routers are between you?
Two, if it sent them with 64 as the lab's machines do: each router lowers it by one.
3. Red has default via 10.0.1.1 and 10.0.2.0/24 via 10.0.1.5. Which gateway does 10.0.2.2 go to?
10.0.1.5: the /24 is longer than default's /0, so it wins.
ip route get 10.0.2.2 confirms it.
Next: Practical 1 · A router between two networks, then lesson 5 · ARP and bridges.
5 · ARP and bridges
In one sentence: on a link, packets are delivered to MAC addresses; ARP finds the MAC that has an IP address by asking everyone on the link, and a bridge is a virtual switch that joins many cables into one link and learns which port each MAC is behind.
The problem it solves
Lesson 3’s route said “10.0.0.0/24 is on veth-red’s link: send directly”. But a frame on a link is addressed to a
MAC address (the hardware address from lesson 2), not to an IP address. Red knows 10.0.0.2; it doesn’t know
which MAC that is. And a veth pair joins exactly two machines; a real network has a dozen on the same link.
Two pieces solve both: ARP answers “which MAC has this IP?”, and a switch lets many machines share one link.
ARP: shout the question, get a private answer
Red asks the whole link: “who has 10.0.0.2? tell 10.0.0.1”. The request goes to the broadcast MAC
ff:ff:ff:ff:ff:ff, which every machine on the link receives. Only the owner answers, straight to red. Here is
red’s first ping to blue, seen from blue (tcpdump -e adds the MACs; timestamps cut):
9e:5f:c1:50:6d:6b > ff:ff:ff:ff:ff:ff, ethertype ARP (0x0806), length 42: Request who-has 10.0.0.2 tell 10.0.0.1, length 28
7e:ef:d2:7a:28:8d > 9e:5f:c1:50:6d:6b, ethertype ARP (0x0806), length 42: Reply 10.0.0.2 is-at 7e:ef:d2:7a:28:8d, length 28
9e:5f:c1:50:6d:6b > 7e:ef:d2:7a:28:8d, ethertype IPv4 (0x0800), length 98: 10.0.0.1 > 10.0.0.2: ICMP echo request, id 2737, seq 1, length 64
Read the left of each line: request to everyone, reply to red, then the ping itself, from red’s MAC to blue’s.
Red stores the answer in its neighbour table (ip neigh), so the next packets skip the question. The entry is
REACHABLE for about 30 seconds, then STALE: still used, but checked again the next time it’s needed.
When nobody answers
Ping an address on the link that no machine has, 10.0.0.9. Red asks three times, a second apart, then gives up:
the neighbour entry becomes FAILED, and the error comes from red itself:
From 10.0.0.1 icmp_seq=1 Destination Host Unreachable
A TCP connection to it fails after about 3 seconds with the message lesson 1 left unexplained:
nc: connect to 10.0.0.9 port 8080 (tcp) failed: No route to host
The name misleads: the route was fine (10.0.0.0/24 is on the link); a missing route is Network is unreachable (lesson 3), and it’s instant. “No route to host” after about 3 seconds
means nobody on the link answered ARP: the machine is off, unplugged, or doesn’t have that address. (The same
words at once come from a firewall rule that rejects with “host prohibited”: lesson 7.)
A bridge: a switch inside the kernel
A bridge is a virtual switch: an interface whose ports are other interfaces. A frame that comes in on one
port goes out of the port where its destination MAC is. The lab’s version puts the switch in its own namespace,
switch, with one veth cable to each machine:
red 10.0.0.1 blue 10.0.0.2 green 10.0.0.3
veth-red veth-blue veth-green
| | |
switch: sw-red ------------- sw-blue -------------- sw-green
\___________________ br0 ___________________/
ip netns add switch
ip -n switch link add br0 type bridge
ip -n switch link set br0 up
ip -n switch link set sw-red master br0
master br0 plugs a port into the switch. bridge -n switch link lists the ports:
3: sw-red@if4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master br0 state forwarding priority 32 cost 2
5: sw-blue@if6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master br0 state forwarding priority 32 cost 2
7: sw-green@if8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master br0 state forwarding priority 32 cost 2
The bridge needs no IP address; red, blue and green have the addresses, all in 10.0.0.0/24, one link.
The switch learns
Each frame that comes in on a port tells the bridge “this MAC is behind this port”. It keeps that in its
forwarding database, bridge -n switch fdb show br br0 (the entries without permanent are the learned ones):
9e:5f:c1:50:6d:6b dev sw-red master br0
7e:ef:d2:7a:28:8d dev sw-blue master br0
6e:fd:8f:a0:41:5f dev sw-green master br0
A broadcast goes out of every port; a frame to a known MAC goes out of one. tcpdump in green during red’s
first ping to blue catches exactly one frame of it, the ARP request:
15:42:09.971304 9e:5f:c1:50:6d:6b > ff:ff:ff:ff:ff:ff, ethertype ARP (0x0806), length 42: Request who-has 10.0.0.2 tell 10.0.0.1, length 28
The reply and the pings went only to the ports of red and blue. (Green’s tcpdump also shows a few IPv6
“router solicitation” frames that new interfaces send by themselves; Practical 2 filters them out with
arp or icmp.)
Unplugged from the switch
ip -n switch link set sw-green nomaster takes green’s port out of the bridge. Green’s own interface still says
UP and LOWER_UP: its cable is plugged in at both ends, into a switch port that leads nowhere. After
ip -n red neigh flush all (red forgets green’s MAC), red’s ping to 10.0.0.3 gets 100% packet loss and the
neighbour entry turns FAILED.
LOWER_UP says the cable is there, not that the switch passes it: bridge link is where the missing port shows.
| What you see | It means | Look at |
|---|---|---|
neighbour REACHABLE / STALE | ARP worked | |
neighbour FAILED, Destination Host Unreachable from yourself | nobody answered ARP | the far machine’s address and link, the switch ports |
No route to host after about 3 s | the same, seen by TCP | same |
Try it on your computer
Practical 2, after lesson 6, builds this switch with three machines on it and puts a service on blue.
Go deeper: docker0 is this bridge
Lesson 2 found your lab container’s other veth end on the host, master docker0. Read docker0 on your server
(read-only, no sudo):
ip -d link show docker0
ip -br link show master docker0
bridge forward_delay 1500 hello_time 200 max_age 2000 ageing_time 30000 stp_state 0 ...
vethbc0bbc6@if2 UP 4e:17:e1:f8:8f:1a <BROADCAST,MULTICAST,UP,LOWER_UP>
A bridge with one port per container; @if2 is, as in lesson 2, the index of the partner, the container’s end. docker0’s own MAC is ea:92:21:b2:12:84, the same MAC lesson 2’s container
had in its neighbour table for its gateway 172.17.0.1. Unlike the lab’s br0, docker0 has an address
(172.17.0.1): the bridge itself is the containers’ gateway, the host’s way into that network. More in
ip-link(8), “bridge”.
Go deeper: the neighbour table's timers
Three settings per interface explain the numbers above (arp(7)):
net.ipv4.neigh.veth-red.base_reachable_time_ms = 30000
net.ipv4.neigh.veth-red.mcast_solicit = 3
net.ipv4.neigh.veth-red.retrans_time_ms = 1000
An answer keeps an entry REACHABLE for a random time between 15 and 45 seconds (half to one and a half times
30). Then it’s STALE; when it’s next used, the kernel checks it again with a unicast ARP, straight to the
MAC it already has. An unanswered address gets 3 broadcast requests, 1 second apart: 3 × 1 s.
Common misunderstandings
- “
Destination Host Unreachablecame from the far machine.” Look at theFrom:10.0.0.1, red itself. Red couldn’t find a MAC for the address. - “Every machine on a switch sees all the traffic.” Only broadcasts (and multicasts), and frames to MACs the switch hasn’t learned yet. Green saw red’s ARP request and none of the pings.
Check yourself
1. ip neigh in red shows 10.0.0.3 dev veth-red FAILED, and green's ip -br link says UP with LOWER_UP. Where do you look next?
At the switch: bridge -n switch link. If sw-green isn't listed, its port is out of the
bridge (ip -n switch link set sw-green master br0 puts it back). Also check that green really has
10.0.0.3.
2. A curl to a server on your network fails after about 3 seconds with "No route to host", but ip route get shows a route. What happened?
ARP got no answer: three requests a second apart. The server is down, unplugged, or not using that address.
3. You run tcpdump on green and want to see red's pings to blue. Will you?
No: after the first ARP request (a broadcast), the bridge sends red's and blue's frames only to each other's
ports. Run it on blue, or on the switch's sw-blue port.
Next: lesson 6 · Ports, sockets and TCP.
6 · Ports, sockets and TCP
In one sentence: a port picks one program on a machine; a server’s listening socket waits on an address and a port, TCP opens every connection with a three-packet handshake, and the error you get says whether something answered “no” (refused) or nothing answered at all (timed out).
The problem it solves
Lessons 3 to 5 got a packet to the right machine: address, route, MAC. But a machine runs many programs, and the packet is for one of them. That’s lesson 1’s fifth question, “which flat in the building?”. When the network is fine and the app still can’t connect, the answer is almost always here: nothing listens on that port, it listens on the wrong address, or the reply never comes back.
The idea: a door number, and someone behind it
A port is a number from 1 to 65535 that names a door on the machine. A server program asks the kernel to
listen on a port; from then on the kernel hands it every new connection to that port. That waiting endpoint is
a socket, and ss lists them (lesson 2’s last table).
In Practical 0’s lab, start a listener in blue with nc (netcat), and look:
ip netns exec blue nc -lk 8080 &
ip netns exec blue ss -tlnp
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 1 0.0.0.0:8080 0.0.0.0:* users:(("nc",pid=2623,fd=3))
-l listen, -k keep listening after a connection ends. In ss, -p adds the program. The local address
0.0.0.0:8080 means port 8080 on every address blue has.
The handshake
A client opens a TCP connection in three packets: SYN (“let’s talk”), SYN-ACK (“yes, let’s”), ACK (“ok”).
Only then does data flow. tcpdump in blue while red sends hello (echo hello | nc -N 10.0.0.2 8080; flags in
[...], the rest of each line cut; -N makes nc close the connection when its input ends):
15:42:07.090971 IP 10.0.0.1.55578 > 10.0.0.2.8080: Flags [S], seq 2026845857, win 64240, ...
15:42:07.090990 IP 10.0.0.2.8080 > 10.0.0.1.55578: Flags [S.], seq 2307351405, ack 2026845858, win 65160, ...
15:42:07.091005 IP 10.0.0.1.55578 > 10.0.0.2.8080: Flags [.], ack 1, win 502, ...
15:42:07.091117 IP 10.0.0.1.55578 > 10.0.0.2.8080: Flags [P.], seq 1:7, ack 1, win 502, ...
| Flag | Name | Means |
|---|---|---|
[S] | SYN | open a connection |
[S.] | SYN-ACK | accepted |
[.] | ACK | got it |
[P.] | PUSH | data (here 6 bytes, hello and a newline) |
[F.] | FIN | I’m done sending |
[R.] | RST | no: reset this connection |
Red used port 55578. A client gets a free ephemeral port from a range the kernel picks from
(ip_local_port_range, here 32768 60999). A second connection, held open, shows in ss -tn on both ends,
mirrored:
ESTAB 0 0 10.0.0.1:54260 10.0.0.2:8080
ESTAB 0 0 10.0.0.2:8080 10.0.0.1:54260
After it closes, the side that closed first (here red) keeps it as TIME-WAIT for a while, so a late packet of the
old connection can’t land in a new one.
Refused: the machine said no
Stop the listener and connect again. The answer comes back at once, as an RST:
15:42:44.006349 IP 10.0.0.1.45344 > 10.0.0.2.8080: Flags [S], seq 435995594, win 64240, ...
15:42:44.006362 IP 10.0.0.2.8080 > 10.0.0.1.45344: Flags [R.], seq 0, ack 435995595, win 0, length 0
nc: connect to 10.0.0.2 port 8080 (tcp) failed: Connection refused
13 microseconds between the two, and no program in blue was involved: blue’s kernel answered for the empty port. Refused means the whole network works: the packet reached the machine and it replied. The problem is the program.
A common way to get it with a server running: it listens on 127.0.0.1 only. Start nc -lk 127.0.0.1 8080
in blue and ss shows the difference:
LISTEN 0 1 127.0.0.1:8080 0.0.0.0:*
From blue itself, nc -zv 127.0.0.1 8080 succeeds (-z only connects and sends nothing, -v prints the
result). From red, Connection refused: red’s SYN arrives for
10.0.0.2:8080, and nothing listens on that address. Always read the Local Address column, not just the port.
Timed out: nothing came back
Now the listener is back on 0.0.0.0, but blue has lost its route back to 10.0.0.0/24 (lesson 4’s trap, on one
link). Red sends a SYN, then sends it again, about every second at first (lesson 1 showed the gaps growing when nothing
limits the wait). tcpdump in blue sees each one arrive, and blue never
answers. Red’s side of it, in ss:
0 1 10.0.0.1:57948 10.0.0.2:8080
(ss -tn state syn-sent: still waiting for a SYN-ACK.) With a 5-second limit (nc -w5):
nc: connect to 10.0.0.2 port 8080 (tcp) timed out: Operation now in progress
Timed out means silence: something on the way, or on the way back, lost the packets. Lesson 7’s firewall
DROP gives the same silence on purpose.
| Error | On the wire | Means | Look at |
|---|---|---|---|
Connection refused, at once | [S], then [R.] back | reached the machine; nothing listens on that address and port | ss -tlnp on the server: the port, and the address |
timed out, after your limit | [S] again and again, nothing back | lost on the way there or back | routes both ways, firewalls (lesson 7) |
Try it on your computer
Practical 2 · A switch and a service: build lesson 5’s switch with three machines, run a service on blue, watch its handshake, then break it two ways and tell them apart.
Go deeper: four numbers name a connection
A connection is identified by four values: source address and port, destination address and port. That’s how one
server port takes thousands of clients: every client connection differs in its source. It also means one client
address can open at most 28,232 connections at once to the same server port (60999 - 32768 + 1, the ephemeral
range), a limit a busy proxy can hit.
TIME-WAIT lasts 60 seconds in Linux, a fixed constant
(TCP_TIMEWAIT_LEN), and holds one of those
ports while it lasts. Four ports in TIME-WAIT after four short connections is normal; tens of thousands is a
client opening a new connection per request.
Go deeper: the kernel does the handshake
The program never sees SYN, SYN-ACK or ACK. It asks the kernel to listen, and the kernel completes handshakes on its own, queueing finished connections until the program takes one (listen(2)). The RST for a closed port comes from the kernel too, which is why it took 13 microseconds and needed no program.
So a connection that opens proves the kernel listens for a program, not that the program will answer it. Lesson
8’s curl asks the program itself.
Common misunderstandings
- “Refused means a firewall blocked it.” A firewall that drops gives a timeout. Refused is an answer: an RST from the machine, usually because nothing listens (lesson 7 shows a firewall that sends RST on purpose).
- “It listens on 8080, so others can reach it.” Only if it listens on an address they can reach.
127.0.0.1:8080serves only the machine itself. - “Timed out means the server is slow.” For a connect, it means no SYN-ACK came back at all.
Check yourself
1. curl to a server fails at once with "Connection refused". The server's admin says "the service is running". What do you ask them to run?
ss -tlnp on the server. Check the port is the one you use, and that the local address is
0.0.0.0 (or the address you connect to), not 127.0.0.1.
2. A connect hangs for the whole timeout. tcpdump on the server shows the SYNs arriving and no SYN-ACKs leaving. Where is the problem?
On the server's side of the way back: its route to you (lesson 4), or a firewall on it dropping (lesson 7). The
way there works, since the SYNs arrive.
3. ss -tan on a client shows hundreds of TIME-WAIT lines to the same server port. Is the network broken?
No: those are connections the client closed, kept for 60 seconds each. It shows a client opening many short
connections.
Next: Practical 2 · A switch and a service, then lesson 7 · Firewalls and NAT.
7 · Firewalls and NAT
In one sentence: the kernel’s packet filter, netfilter, runs every packet past lists of rules; a rule can let it through, throw it away (DROP: the sender hears nothing) or refuse it (REJECT: the sender gets an answer), and NAT rules rewrite addresses, which is how Docker lets containers out and publishes their ports.
The problem it solves
Lesson 1’s fourth failure was curl: (28) Connection timed out after 5002 milliseconds: a firewall threw the
packets away. Firewalls are deliberate: a server should accept connections to its service and nothing else. But a
rule written too wide, or in the wrong place, looks exactly like a broken network. You need to read rules, write
them, and know which symptom each kind of rule produces.
Two more everyday problems live in the same machinery. A container’s private address (172.17.x.x) can’t be
answered from the internet, yet it reaches it. And docker run -p makes a container’s port reachable on the
server’s address. Both are address rewriting: NAT.
The idea: a guard with a checklist
Picture a guard at each door of the machine with a list of rules. Each packet is compared with the rules from the top; the first rule that matches decides. If none matches, the chain’s policy (its default) decides.
The doors are chains, each at a point in the packet’s path through the kernel:
packet in ──► PREROUTING ──► for me? ──yes──► INPUT ──► program
(nat: DNAT) │
no
▼
FORWARD ──► POSTROUTING ──► packet out
(nat: MASQUERADE)
program ──► OUTPUT ──────────────────────► POSTROUTING
| Chain | Sees packets | Use it for |
|---|---|---|
INPUT | for this machine | protecting a server |
FORWARD | passing through (a router) | filtering between networks |
OUTPUT | sent by this machine | limiting what it sends |
PREROUTING (nat) | as they arrive | rewriting the destination (DNAT) |
POSTROUTING (nat) | as they leave | rewriting the source (MASQUERADE) |
The tool is iptables. Here it is iptables v1.8.11 (nf_tables): it writes its rules into nftables, the
kernel’s current rule engine, which nft reads and writes directly.
DROP: silence
The lab: Practical 1’s red, router and blue, with nc -lk 8080 running in blue. Block the port on blue:
ip netns exec blue iptables -A INPUT -p tcp --dport 8080 -j DROP
-A INPUT appends to the INPUT chain, -p tcp --dport 8080 matches TCP to port 8080, -j DROP is the verdict.
From red:
nc: connect to 10.0.2.2 port 8080 (tcp) timed out: Operation now in progress
after 5 seconds (-w5). tcpdump in blue sees each SYN arrive, and nothing goes back. -L -n -v lists the rules
with counters, the quickest proof that a rule is the one catching your packets:
pkts bytes target prot opt in out source destination
8 480 DROP tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8080
Ping still works: the rule matches only TCP port 8080.
REJECT: an answer
Replace DROP with REJECT, and red gets an answer at once, in 0.003 s:
nc: connect to 10.0.2.2 port 8080 (tcp) failed: Connection refused
On the wire, blue sent an ICMP error instead of silence:
16:18:00.416206 IP 10.0.2.2 > 10.0.1.2: ICMP 10.0.2.2 tcp port 8080 unreachable, length 68
With -j REJECT --reject-with tcp-reset the answer is a TCP RST, Flags [R.], exactly what a closed port sends.
So “Connection refused” can come from a firewall too: lesson 6’s rule (“refused = something answered”) still
holds, but the something may be a REJECT rule. iptables -L -n -v on the server tells them apart.
| Verdict | Sender sees | After |
|---|---|---|
DROP | timed out | its whole time limit |
REJECT | Connection refused (ICMP port unreachable) | at once |
REJECT --reject-with tcp-reset | Connection refused (RST) | at once |
REJECT --reject-with icmp-host-prohibited | No route to host (ICMP host unreachable, admin prohibited) | at once |
A REJECT’s No route to host comes at once; lesson 5’s unanswered ARP takes about 3 seconds.
The right chain, on the right machine
The same DROP in the router’s FORWARD chain (-d 10.0.2.2 -p tcp --dport 8080) gives red the same timeout, and the
router’s rule counts the SYNs (3 180 DROP ... 10.0.2.2 tcp dpt:8080); a DROP rule on blue would count none,
because they never reach it. A firewall can be on any machine on the path, and the rule counters show which one
is dropping.
A server’s firewall usually starts from default deny: drop everything, then allow what you mean.
-P INPUT DROP
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 8080 -j ACCEPT
Red’s nc to 8080 succeeds, and red’s ping to blue gets 100% packet loss. The ESTABLISHED line lets in replies
to connections blue started itself, so blue can still ping out.
NAT: rewriting addresses
Now take away blue’s route back to red (ip -n blue route del default): red’s connection times out, as in lesson 4.
Instead of a route, have the router put its own address on red’s packets as they leave towards blue:
ip netns exec router iptables -t nat -A POSTROUTING -s 10.0.1.0/24 -o r-blue -j MASQUERADE
The connection works. tcpdump on blue’s veth-blue sees it coming from the router:
16:18:35.195561 IP 10.0.2.1.40864 > 10.0.2.2.8080: Flags [S], seq 1982517039, win 64240, ...
and on red’s veth-red (a second connection), red’s SYN still carries its own address:
16:18:36.324131 IP 10.0.1.2.40870 > 10.0.2.2.8080: Flags [S], seq 3671444475, win 64240, ...
Blue answers 10.0.2.1, on its own link, and the router passes the reply back to red. That’s MASQUERADE,
source NAT, and it’s how every container on docker0 reaches the internet with your server’s address.
The other direction is DNAT, destination NAT: a port forward. Make the router’s 10.0.1.1:9090 lead to blue’s
8080:
ip netns exec router iptables -t nat -A PREROUTING -i r-red -p tcp --dport 9090 -j DNAT --to-destination 10.0.2.2:8080
nc -zv 10.0.1.1 9090 from red succeeds, and blue sees 10.0.1.2 > 10.0.2.2.8080: the destination was rewritten,
the source kept. Port 8080 on 10.0.1.1 is still Connection refused: only 9090 is forwarded. A DNAT’d packet is still forwarded, so with net.ipv4.ip_forward=0 in the router it times out
again. This is docker run -p 9090:8080.
Try it on your computer
The capstone, Practical 3 · Capstone: netcheck, has the checker add rules like these to your lab. From the client, a REJECT shows itself (refused at once); a DROP looks exactly like a missing route back (timed out), so your script has to look on the far machines, at rule counters and routes, to tell those apart.
Go deeper: what iptables wrote into nftables
nft list ruleset shows the DROP rule above as iptables stored it:
table ip filter {
chain INPUT {
type filter hook input priority filter; policy accept;
tcp dport 8080 counter packets 8 bytes 480 drop
}
}
A table holds chains; a chain attached to a hook (input, forward, prerouting…) sees the packets at
that point. iptables names its chains in capitals and adds a counter to every rule. The same rule written with
nft itself, in your own table:
nft add table inet lab
nft add chain inet lab input "{ type filter hook input priority 0; }"
nft add rule inet lab input tcp dport 8080 drop
inet covers IPv4 and IPv6 at once. For tables iptables made, nft warns
# Warning: table ip nat is managed by iptables-nft, do not touch!: change those with iptables, and use your own
tables for nft (nft(8)).
Go deeper: what Docker does with these
Docker’s documentation describes the same pieces on your server’s host side: “Docker creates firewall rules to implement network isolation, port publishing and filtering” (packet filtering and firewalls); “outgoing packets from containers are masqueraded”, and a published port is “a firewall rule in the host, mapping a container port to a port on the Docker host” (port publishing).
It also turns on net.ipv4.ip_forward on the host and, when it does, sets the FORWARD chain’s policy to DROP,
then allows its own containers’ traffic. Your own rules for container traffic belong in the DOCKER-USER chain,
which runs before Docker’s (Docker with iptables).
This course reads the host only; its own rules stay in the lab container.
NAT and ESTABLISHED both rest on connection tracking: the kernel remembers each connection, so the reply to a
masqueraded packet is rewritten back, and a reply matches ESTABLISHED
(iptables-extensions(8), conntrack).
Common misunderstandings
- “Refused means there’s no firewall.” A REJECT rule answers with exactly the same error. Counters on the server’s rules say whether a rule caught it.
- “The server’s rules are the only ones that matter.” A FORWARD rule on any router on the path drops the packets before the server ever sees them.
- “A port forward is just one DNAT rule.” The packet is then forwarded like any other: it needs
ip_forward=1, a FORWARD chain that allows it, and a route back from the server.
Check yourself
1. A connection to port 5432 hangs until the client's timeout. tcpdump on the server shows the SYNs arriving. What do you look at first?
The server's INPUT rules with counters: iptables -L INPUT -n -v. A DROP rule whose packet count
grows with each attempt is the cause. (If the counters don't move, check the route back, lesson 4.)
2. You want a blocked port to fail fast for clients instead of hanging. Which rule?
-j REJECT (optionally --reject-with tcp-reset): the client gets "Connection refused" at once
instead of waiting for its timeout.
3. A container reaches the internet, but tcpdump on the remote server shows the connection coming from your server's address, not the container's 172.17.x.x. Is something wrong?
No: that's MASQUERADE. The host rewrote the source as the packet left, and rewrites the reply back.
Next: lesson 8 · What really happens when you run curl.
8 · What really happens when you run curl
In one sentence: before a single packet goes to the server,
curlturns the name into an address (the hosts file first, then a DNS server on UDP port 53); after that, every step of lessons 3 to 7 happens in order, and onetcpdumpshows them all.
The problem it solves
Lesson 1 started with curl http://web:8080/ failing five ways. The first was
curl: (6) Could not resolve host: web: no packet to web was ever sent, because nothing could say which address
web is. People and config files use names; packets carry addresses. This lesson fills in that first step, then
follows one request all the way, so you can see each question of lesson 1 answered on the wire.
The idea: a phone book, checked in order
Turning a name into an address is resolving it. A program asks the system’s resolver, which looks in two
places, in the order /etc/nsswitch.conf gives:
hosts: files dns
- files:
/etc/hosts, a local list ofaddress namelines; - dns: a DNS server, whose address is in
/etc/resolv.conf, asked over UDP port 53.
getent hosts <name> looks a name up through the same path a program uses (the hosts file, then DNS);
getent ahosts <name> makes the same call as most programs, curl among them (getaddrinfo). dig <name> asks
a DNS server directly and skips /etc/hosts. That difference matters below.
Your lab container’s resolver
Docker wrote the lab container’s /etc/resolv.conf from your server’s:
# Generated by Docker Engine.
...
nameserver 169.254.169.254
search .
...
dig example.com sends one question there and prints the answer (shortened):
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 23060
example.com. 300 IN A 172.66.147.243
example.com. 300 IN A 104.20.23.154
;; Query time: 15 msec
;; SERVER: 169.254.169.254#53(169.254.169.254) (UDP)
status: NOERROR means it found the name; each A line is an IPv4 address; SERVER says who answered.
A DNS server for the lab
This lesson’s lab is Practical 2’s switch with a small DNS server, dnsmasq, on green (10.0.0.3), answering
web.lab with blue’s address, and a web service on blue. Read along here; Practical 3 has you build this lab, with
dnsmasq, yourself. ip netns exec uses
/etc/netns/<name>/resolv.conf, when it exists, as the namespace’s resolv.conf, so red can get its own:
mkdir -p /etc/netns/red && echo "nameserver 10.0.0.3" > /etc/netns/red/resolv.conf
ip netns exec red dig web.lab
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
web.lab. 0 IN A 10.0.0.2
;; SERVER: 10.0.0.3#53(10.0.0.3) (UDP)
curl -v shows the resolver’s answer before it connects:
* Host web.lab:8080 was resolved.
* IPv6: (none)
* IPv4: 10.0.0.2
* Trying 10.0.0.2:8080...
When dig and your program disagree
Add a line 10.0.0.9 web.lab to red’s hosts file (/etc/netns/red/hosts). Now:
| Ask | Answer |
|---|---|
getent hosts web.lab | 10.0.0.9 web.lab (files come first) |
dig +short web.lab | 10.0.0.2 (DNS only) |
curl http://web.lab:8080/ | Failed to connect to web.lab port 8080 after 3088 ms |
curl uses the resolver, gets 10.0.0.9, and fails after 3 seconds, the same failure as lesson 1’s 10.0.0.9 row
(lesson 5: nobody answers ARP for it). When dig
looks right and the program still goes somewhere else, look in /etc/hosts. Take the line out again:
rm /etc/netns/red/hosts.
When resolving fails
Could not resolve host covers several different failures:
| What’s wrong | dig says | curl | after |
|---|---|---|---|
| the server has no answer for the name | status: REFUSED for nosuch.lab | Could not resolve host: nosuch.lab | 0.009 s |
| the DNS server program is stopped | communications error to 10.0.0.3#53: connection refused | Could not resolve host: web.lab | 0.009 s or 5.015 s |
resolv.conf names an address with no server | communications error to 10.0.0.9#53: timed out | Could not resolve host: web.lab | 6.136 s |
In the first row, green’s dnsmasq runs with --no-resolv: with no server to pass other names on to, it
refuses them. One in charge of all of .lab says NXDOMAIN. The second row is lesson 6’s “refused” for UDP: green’s kernel answers the query with
ICMP 10.0.0.3 udp port 53 unreachable. In the third, nothing answers at that address at all.
curl prints the same words in both, so ask dig, which names the server it tried and says which:
connection refused at once, or timed out after its limit.
With the server stopped, the wait depends on those ICMP answers. Green’s kernel sends only a few in a row to one
address (net.ipv4.icmp_ratelimit); a query left without one waits 5 s. So curl took 5.015 s right after other
lookups, 0.009 s alone.
The whole path, in one tcpdump
Red’s first curl http://web.lab:8080/, after ip -n red neigh flush all, watched on veth-red (options cut):
16:18:06.929323 ARP, Request who-has 10.0.0.3 tell 10.0.0.1, length 28
16:18:06.929353 ARP, Reply 10.0.0.3 is-at 82:3d:76:53:5e:58, length 28
16:18:06.929355 IP 10.0.0.1.42557 > 10.0.0.3.53: 58341+ A? web.lab. (25)
16:18:06.929381 IP 10.0.0.1.42557 > 10.0.0.3.53: 30187+ AAAA? web.lab. (25)
16:18:06.929474 IP 10.0.0.3.53 > 10.0.0.1.42557: 58341* 1/0/0 A 10.0.0.2 (41)
16:18:06.929498 IP 10.0.0.3.53 > 10.0.0.1.42557: 30187 Refused 0/0/0 (25)
16:18:06.929615 ARP, Request who-has 10.0.0.2 tell 10.0.0.1, length 28
16:18:06.929636 ARP, Reply 10.0.0.2 is-at 4a:ef:fa:45:62:f5, length 28
16:18:06.929638 IP 10.0.0.1.40736 > 10.0.0.2.8080: Flags [S], ...
16:18:06.929657 IP 10.0.0.2.8080 > 10.0.0.1.40736: Flags [S.], ...
16:18:06.929668 IP 10.0.0.1.40736 > 10.0.0.2.8080: Flags [.], ...
16:18:06.929720 IP 10.0.0.1.40736 > 10.0.0.2.8080: Flags [P.], seq 1:77, ...
16:18:06.929739 IP 10.0.0.2.8080 > 10.0.0.1.40736: Flags [P.], seq 1:45, ...
16:18:06.929773 IP 10.0.0.2.8080 > 10.0.0.1.40736: Flags [F.], ...
Read it against lesson 1’s six questions:
| Lines | Question | Lesson |
|---|---|---|
(before any packet) a route to 10.0.0.3, then to 10.0.0.2 | 2 · which way? | 3, 4 |
ARP for 10.0.0.3 | 3 · who on the link? | 5 |
A? web.lab. and its answer A 10.0.0.2 | 1 · which address? | 8 |
ARP for 10.0.0.2 | 3 · who on the link? | 5 |
[S], [S.], [.] (no firewall dropped them) | 4, 5 · let through? listening? | 7, 6 |
[P.] 76 bytes out (GET /), 44 bytes back (HTTP/1.0 200 OK) | 6 · does the program answer? | this one |
The page leaves out three pure ACKs and red’s FIN: 18 packets in all, 0.48 ms from the first ARP to the last ACK. The handshake only proved the kernel listens (lesson 6); the 44-byte reply is the program itself answering. This order is the order the capstone’s script checks things in.
Try it on your computer
The capstone, Practical 3 · Capstone: netcheck, builds this lab, with a router in front of blue so a route can break too, and has you write a script that asks the six questions in this order and names the first one that fails.
Go deeper: reading dig, and why the AAAA was refused
status is the server’s verdict: NOERROR (found), NXDOMAIN (the name doesn’t exist), REFUSED (this server
won’t answer it), SERVFAIL (it tried and failed). In flags, aa means the answer is authoritative: green’s
dnsmasq is the source for web.lab itself. The 0 before IN A in web.lab. 0 IN A is the TTL: how many
seconds the answer may be cached (300 for example.com).
curl asked for both A (IPv4) and AAAA (IPv6) at once, from the same port. The lab’s dnsmasq knows only
web.lab’s IPv4 address and refused the AAAA; curl -v shows that as IPv6: (none) and carries on with IPv4.
The dig manual and
resolv.conf(5) have the rest.
Go deeper: per-namespace files, and timing a request
ip netns exec red bind-mounts every file in /etc/netns/red/ over the same name in /etc for the command it
runs (ip-netns(8)): ip netns exec red cat /etc/resolv.conf prints nameserver 10.0.0.3 while the container’s own file is unchanged. Docker, likewise,
generates each container’s own resolv.conf (“Generated by Docker Engine”, above).
curl -w prints how long each step took, in seconds since the start:
ip netns exec red curl -sS -o /dev/null -w "dns %{time_namelookup} connect %{time_connect} total %{time_total}\n" http://web.lab:8080/
dns 0.000573 connect 0.000675 total 0.000755
On a slow request, this splits “slow DNS” from “slow connect” from “slow server” in one line.
Common misunderstandings
- “
digworks, so the app will resolve it the same way.”digskips/etc/hosts; programs don’t. Usegetent ahoststo see what programs get. - “
Could not resolve hostmeans the name doesn’t exist.” It also means the DNS server is down or unreachable.dignames the server it tried and says refused or timed out. - “If the name resolves, the problem is the network.” The address could be the wrong one (a stale hosts line), and everything after it then fails for a reason that has nothing to do with the real server.
Check yourself
1. curl http://api:8080/ fails with "Could not resolve host" after about 5 seconds. dig api says connection refused. What's wrong?
The DNS server: its machine is up (it answered with an ICMP "port unreachable"), but no DNS program listens on
port 53. Check the server named in /etc/resolv.conf.
2. dig +short db says 10.0.5.20, but your app keeps connecting to 10.0.9.9. Where do you look?
/etc/hosts (or whatever getent hosts db shows): files come before DNS, and
dig never reads them.
3. In a tcpdump of a failing request you see the DNS answer and an ARP reply, then [S] three times and nothing back. Which question failed?
"Let through?" (or the route back): the name, route and neighbour all worked, and the SYNs got no answer. A
firewall dropping them (lesson 7) or a missing route back (lesson 4).
Next: Practical 3 · Capstone: netcheck.
Practical 0 · Your lab: two namespaces and a cable
Goal: a lab container you built yourself with the network tools in it, two “machines” (
redandblue, network namespaces) joined by a veth cable that you can ping across, a cable you unplug on purpose and diagnose, and a script that rebuilds it all.Time: ~40 minutes. Where: files in
~/linux-networking-zero/on your computer; network commands inside the lab container (./on). Needs Docker Engine on your server and a few hundred MB of disk for the image and the tools. Read lesson 1 and lesson 2 first.
Task 1 · Get the lab script
Make the folder everything in this course goes into, download this course’s lab script into it, and run it:
mkdir -p ~/linux-networking-zero
cd ~/linux-networking-zero
curl -fo lab http://localhost:8800/linux-networking-zero/tools/lab
chmod +x lab
./lab setup p0
✓ Docker 29.1.3 is running (linux/aarch64)
✓ the name netlab is free for your lab container
Building the lab is this practical’s topic, so setup only checks that Docker runs and that the name netlab is
free. Your Docker version and architecture may differ. Every command the lab script runs goes to lab.log.
Task 2 · Start your lab machine
Start a container yourself with these requirements:
- name and hostname
netlab, from the imageubuntu:26.04(newest Ubuntu images) - privileged, so you can change network settings inside it
- the label
fromzero.course=linux-networking-zero(./lab resetonly touches a container that has it) - your folder
~/linux-networking-zeromounted at the same path inside, and as its working directory - it runs
sleep infinity(it only needs to stay up), with--initsodocker stopis instant
Then install the tools into it: iproute2 iputils-ping tcpdump iptables nftables dnsutils netcat-openbsd curl procps.
Hint
docker run -d with --name, --hostname, --privileged, --init, --label, -v "$HOME/...:$HOME/..." and -w,
then the image and the command. For the tools: docker exec netlab bash -c 'apt-get update && apt-get install -y ...',
with DEBIAN_FRONTEND=noninteractive so no installer stops to ask a question.
Solution
docker run -d --name netlab --hostname netlab --privileged --init \
--label fromzero.course=linux-networking-zero \
-v "$HOME/linux-networking-zero:$HOME/linux-networking-zero" -w "$HOME/linux-networking-zero" \
ubuntu:26.04 sleep infinity
docker exec netlab bash -c 'apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \
iproute2 iputils-ping tcpdump iptables nftables dnsutils netcat-openbsd curl procps'
| Flag | Why |
|---|---|
--privileged | lets you create namespaces and change their settings. It also lets the container change your computer’s kernel, so use it only for this lab |
--init | a tiny first process that passes on docker stop, so docker stop takes 0.156 s instead of 10.3 s |
-v same path, -w | scripts you write in ~/linux-networking-zero run inside under the same name |
Now write ~/linux-networking-zero/on, a 5-line script: ./on alone opens a shell in netlab, and
./on <command> runs one command there. Make it executable.
Solution
#!/bin/sh
# on [command ...]: a shell in your lab container netlab, or one command there
t=; [ -t 0 ] && t=-t
if [ $# -eq 0 ]; then exec docker exec -it netlab bash; fi
exec docker exec -i $t netlab bash -c "$*"
-i passes your input in, -t gives a terminal (only when you have one, so the lab script can use ./on too).
chmod +x on
./on hostname
It prints netlab. From here on, commands in a bash block run inside the lab: open a shell there with ./on
(your prompt becomes root@netlab:...#) and type them; exit leaves it.
Task 3 · Look around
Predict first: how many interfaces does a fresh container have, and what is its default route?
ip -br link
ip -br addr
ip route
What you see
lo UNKNOWN 00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP>
eth0@if837 UP 66:f3:e2:83:c1:cf <BROADCAST,MULTICAST,UP,LOWER_UP>
lo UNKNOWN 127.0.0.1/8 ::1/128
eth0@if837 UP 172.17.0.2/16
default via 172.17.0.1 dev eth0
172.17.0.0/16 dev eth0 proto kernel scope link src 172.17.0.2
Two interfaces: lo and eth0, Docker’s cable into the container. Your number after @if, your MAC and your
172.17.x.x address may differ. ip route shows default via 172.17.0.1 dev eth0: everything leaves through Docker’s gateway. This is
lesson 2’s container stack: you’re looking at its interfaces, addresses and routes tables.
Task 4 · Two machines and a cable
Build, inside the lab:
- two network namespaces,
redandblue - a veth pair with ends
veth-red(inred) andveth-blue(inblue) 10.0.0.1/24onveth-red,10.0.0.2/24onveth-blue
Don’t bring anything up yet.
Hint
ip netns add, ip link add ... type veth peer name ..., ip link set <dev> netns <ns>, then
ip -n <ns> addr add <cidr> dev <dev>. Lesson 2 has each one.
Predict first: with every interface still down, what does
ip netns exec red ping -c1 -W2 10.0.0.2print? And with onlyveth-redup?
ip netns exec red ping -c1 -W2 10.0.0.2
ip -n red link set veth-red up
ip netns exec red ping -c1 -W2 10.0.0.2
What you see
All down: ping: connect: Network is unreachable, at once. The address is on a link that’s down, so red has no
route to 10.0.0.0/24 (ip -n red route prints nothing).
Only red’s end up: the route appears, marked linkdown, and the ping waits 2 s and reports
1 packets transmitted, 0 received, 100% packet loss. Red sent into a cable whose other end is off.
Now bring up everything else (lo in both, veth-blue) and ping again.
Solution
ip netns add red
ip netns add blue
ip link add veth-red type veth peer name veth-blue
ip link set veth-red netns red
ip link set veth-blue netns blue
ip -n red addr add 10.0.0.1/24 dev veth-red
ip -n blue addr add 10.0.0.2/24 dev veth-blue
ip -n red link set lo up
ip -n red link set veth-red up
ip -n blue link set lo up
ip -n blue link set veth-blue up
ip netns exec red ping -c3 10.0.0.2
ip -n red neigh
Replies, and red’s neighbour table holds blue’s MAC: compare it with ip -n blue link show veth-blue.
The first ping may say From 10.0.0.1 icmp_seq=1 Destination Host Unreachable; the next ones get replies. That’s
left over from the predict step: its ping asked for blue’s MAC (ARP) while nobody could answer, and red keeps asking
for about 3 s (INCOMPLETE in ip -n red neigh). A ping sent near the end waits on that attempt, which gives up
and drops it. Wait 3 s after a failed ping and the first ping gets a reply.
Task 5 · Break it: unplug the cable
Switch off blue’s end, as if someone pulled the cable out of blue:
ip -n blue link set veth-blue down
ip netns exec red ping -c2 -W1 10.0.0.2
The ping only says 100% packet loss. Find out why from red’s side only, reading lesson 2’s tables starting at the cable:
- Interfaces:
ip -n red -br link. Look forNO-CARRIERin red’s flags: your end is up, nothing is on the other end. The state column may sayDOWNhere, orLOWERLAYERDOWNas in lesson 2; the flag is what counts. - Routes:
ip -n red route. The10.0.0.0/24route is still there, markedlinkdown. - Neighbours:
ip -n red neigh. Red’s entry for 10.0.0.2 no longer shows a MAC.
The first “no” (step 1) is the answer: the cable. Fix it with ip -n blue link set veth-blue up and ping again. The
very first ping after the fix may still report Destination Host Unreachable, as in task 4: within about 3 s of
the failed ping, red’s unanswered ARP attempt (INCOMPLETE) is still running, gives up, and drops the new ping
with it. The next ones get replies.
Task 6 · Put it in a script
Predict first: you restart the container (
docker restart netlab). Areredandbluestill there?
docker restart netlab
./on ip netns exec red ip -br link
Run these on your computer, not inside the lab (leave the lab shell with exit first), and the ones below too. You get
setting the network namespace "red" failed: Invalid argument. The namespaces died with the container’s processes,
and only their names in /run/netns are left (lesson 2, Go deeper).
Write ~/linux-networking-zero/p0.sh yourself:
- builds task 4’s lab from nothing, with everything up
- safe to run again: it first deletes
redandblueif they exist, alive or dead, without printing errors - stops at the first command that fails
Hint
set -e stops at the first failure. ip netns del red 2>/dev/null || true deletes a namespace without failing when
there isn’t one.
Solution
#!/bin/bash
# p0.sh: two namespaces, red and blue, joined by a veth cable (Practical 0)
set -e
ip netns del red 2>/dev/null || true
ip netns del blue 2>/dev/null || true
ip netns add red
ip netns add blue
ip link add veth-red type veth peer name veth-blue
ip link set veth-red netns red
ip link set veth-blue netns blue
ip -n red addr add 10.0.0.1/24 dev veth-red
ip -n blue addr add 10.0.0.2/24 dev veth-blue
ip -n red link set lo up
ip -n red link set veth-red up
ip -n blue link set lo up
ip -n blue link set veth-blue up
./on bash p0.sh
./on bash p0.sh
./on ip netns exec red ping -c1 10.0.0.2
Running it twice proves it’s safe to run again; the ping proves the lab is back. After any restart of netlab,
./on bash p0.sh is all you need.
Check your work
./lab check p0
All 26 checks should pass.
Go deeper: what "privileged" changes here
In an ordinary container, the very first command of task 4 fails:
mount --make-shared /run/netns failed: Operation not permitted
Adding just the capabilities NET_ADMIN and SYS_ADMIN still isn’t enough (the same line, ending
Permission denied): Docker restricts containers in more ways than capabilities. Privileged lifts all of
them. Network settings belong to the namespace they’re set in, so changing one in red (lessons 4 and 7 set
net.ipv4.ip_forward) changes nothing on your computer.
The kernel, though, is your computer’s one kernel. When iptables or nft in the lab needs a part of the kernel
that isn’t loaded yet (a module: nf_tables, nf_nat, nf_conntrack…), it is loaded there, and it stays loaded
after the rule and the namespace are gone (grep nf_ /proc/modules, on your computer or in the lab, shows the same
list).
Privileged also gives the container every other power over the kernel, which is why it is for this lab and nothing else. To start over at any
time: docker rm -f netlab, then task 2.
Next: lesson 3 · IP addresses and subnets, then Practical 1 · A router between two networks.
Practical 1 · A router between two networks
Goal: three machines (
red,router,blue) on two networks, routes that send red’s and blue’s traffic through the router, forwarding switched off and on, and a missing route back that you find withip route getandtcpdump, all rebuilt by one script,p1.sh.Time: ~40 minutes. Where: files in
~/linux-networking-zero/on your computer; network commands inside the lab container (./on). Read lesson 3 and lesson 4 first.
Skipped Practical 0, or your lab is in a state you don’t trust? ./lab reset p1 (on your computer) deletes every
namespace in netlab and rebuilds Practical 0’s red and blue. It needs the lab container from Practical 0, task 2.
As in Practical 0, commands in a bash block run inside the lab: open a shell there with ./on. The ones
that start with ./on or ./lab run on your computer.
Task 1 · Two networks and a router
Write ~/linux-networking-zero/p1.sh yourself:
- deletes
red,blueandrouterif they exist (Practical 0’s red and blue too), without errors, and stops at the first command that fails, likep0.sh - three namespaces:
red,router,blue - a cable from
veth-red(in red) tor-red(in router), and one fromveth-blue(in blue) tor-blue(in router) - addresses: red
10.0.1.2/24, router10.0.1.1/24onr-redand10.0.2.1/24onr-blue, blue10.0.2.2/24 - every interface up,
loincluded; no routes yet
red router blue
veth-red 10.0.1.2/24 --- r-red 10.0.1.1/24
r-blue 10.0.2.1/24 --- veth-blue 10.0.2.2/24
Hint
Start from p0.sh: one more ip netns del and ip netns add, two ip link add ... type veth peer name ..., and
each end moved with ip link set <end> netns <namespace>. The router’s two ends both go into router.
Solution
#!/bin/bash
# p1.sh: red and blue on two networks, joined by router (Practical 1)
set -e
ip netns del red 2>/dev/null || true
ip netns del blue 2>/dev/null || true
ip netns del router 2>/dev/null || true
ip netns add red
ip netns add router
ip netns add blue
ip link add veth-red type veth peer name r-red
ip link set veth-red netns red
ip link set r-red netns router
ip link add veth-blue type veth peer name r-blue
ip link set veth-blue netns blue
ip link set r-blue netns router
ip -n red addr add 10.0.1.2/24 dev veth-red
ip -n router addr add 10.0.1.1/24 dev r-red
ip -n router addr add 10.0.2.1/24 dev r-blue
ip -n blue addr add 10.0.2.2/24 dev veth-blue
ip -n red link set lo up
ip -n red link set veth-red up
ip -n router link set lo up
ip -n router link set r-red up
ip -n router link set r-blue up
ip -n blue link set lo up
ip -n blue link set veth-blue up
./on bash p1.sh
Predict first: which of these works from red: a ping to the router (
10.0.1.1), a ping to blue (10.0.2.2)?
ip netns exec red ping -c1 -W1 10.0.1.1
ip netns exec red ping -c1 -W1 10.0.2.2
ip -n red route get 10.0.2.2
What you see
The router answers: it’s on red’s own link. Blue doesn’t, and no packet even leaves:
ping: connect: Network is unreachable
RTNETLINK answers: Network is unreachable
ip -n red route has one line, 10.0.1.0/24 dev veth-red ...: red knows its own network and nothing else.
Task 2 · Routes both ways
Give red a default route through the router, and blue one through the router’s other address. Then ask red’s kernel which way it would send to blue.
Hint
ip -n <ns> route add default via <the router's address on your network>.
Solution
ip -n red route add default via 10.0.1.1
ip -n blue route add default via 10.0.2.1
ip -n red route get 10.0.2.2
10.0.2.2 via 10.0.1.1 dev veth-red src 10.0.1.2 uid 0
Add the two lines to the end of p1.sh, so the script matches what you built.
Task 3 · Forwarding off, then on
In the lab, new namespaces start with forwarding on (they copy it from your computer, where Docker Engine turned it on), so switch it off in the router first and see what that does.
Predict first: with forwarding off, does red get an error, or silence? On which of the router’s two sides will
tcpdumpsee red’s pings?
ip netns exec router sysctl -w net.ipv4.ip_forward=0
ip netns exec router timeout 6 tcpdump -n -c 3 -i r-red icmp & sleep 1; ip netns exec red ping -c3 -W1 10.0.2.2; wait
ip netns exec router timeout 6 tcpdump -n -c 3 -i r-blue icmp & sleep 1; ip netns exec red ping -c3 -W1 10.0.2.2; wait
Why: & starts tcpdump in the background, sleep 1 gives it time to start, wait waits for it to finish.
-c 3 stops after three packets, timeout 6 after six seconds when fewer come.
What you see
Silence: 3 packets transmitted, 0 received, 100% packet loss, and no error line. On r-red tcpdump catches three
ICMP echo requests; on r-blue, 0 packets captured. The router takes red’s packets in and drops them.
Now switch it on, and look at the replies:
ip netns exec router sysctl -w net.ipv4.ip_forward=1
ip netns exec red ping -c3 10.0.2.2
ip netns exec red ping -c1 -W1 -t1 10.0.2.2
The replies say ttl=63: one router lowered blue’s 64 by one. With -t1 (TTL 1) the ping dies at the first router, and the
router says so: From 10.0.1.1 icmp_seq=1 Time to live exceeded. Add the sysctl -w ... =1 line to p1.sh
(as ip netns exec router sysctl -w net.ipv4.ip_forward=1), then run it again from your computer: ./on bash p1.sh
twice, and red’s ping to blue still works.
Task 4 · Break it: the way back
Run this, without reading it closely: it’s what a colleague did.
ip -n blue route del default
Red’s ping to blue now fails. Find the cause using only these, in this order, and write down what each says:
- red’s own route:
ip -n red route get 10.0.2.2 - the router:
ip netns exec router sysctl net.ipv4.ip_forward - does it arrive?
ip netns exec blue timeout 6 tcpdump -n -c 6 -i veth-blue icmp & sleep 1; ip netns exec red ping -c3 -W1 10.0.2.2; wait - blue’s way back:
ip -n blue route get 10.0.1.2
What each says
1 and 2 are fine: via 10.0.1.1, ip_forward = 1. In 3 tcpdump sees three echo requests arrive and no
echo reply leave. 4 says why: RTNETLINK answers: Network is unreachable. Blue gets the requests and has no
route to send the replies.
Fix it with the same command as task 2 (ip -n blue route add default via 10.0.2.1). p1.sh still has that line,
so it already matches; run ./on bash p1.sh to be sure the script and the lab agree.
Check your work
./lab check p1
All 31 checks should pass. They read your namespaces, routes and forwarding setting, ping blue from red (and look for
ttl=63), and read p1.sh.
Go deeper: watch the router rewrite the packet
The router changes two things in every packet it forwards: the TTL (one lower) and the Ethernet addresses (the
frame leaving r-blue is from the router’s MAC to blue’s). The IP addresses stay 10.0.1.2 > 10.0.2.2. -e
shows the Ethernet header, -v the TTL:
ip netns exec router timeout 6 tcpdump -n -e -v -c 2 -i r-blue icmp & sleep 1; ip netns exec red ping -c1 10.0.2.2; wait
Compare the MACs with ip -n router link show r-blue and ip -n blue link show veth-blue. Lesson 5 shows how the
router found blue’s MAC.
Next: lesson 5 · ARP and bridges.
Practical 2 · A switch and a service
Goal: three machines on one switch (a bridge), a TCP service on blue that red and green can reach, its handshake caught with
tcpdump, and two breaks you tell apart by their errors: a service on the wrong address, and a machine unplugged from the switch. All rebuilt byp2.sh.Time: ~45 minutes. Where: files in
~/linux-networking-zero/on your computer; network commands inside the lab container (./on). Read lesson 5 and lesson 6 first.
Skipped a practical, or your lab is in a state you don’t trust? ./lab reset p2 (on your computer) deletes every
namespace in netlab and rebuilds what Practicals 0 and 1 built.
As before, commands in a bash block run inside the lab (./on opens a shell there); the ones starting with
./on or ./lab run on your computer.
Task 1 · A switch with three machines
Write ~/linux-networking-zero/p2.sh yourself:
- starts clean like
p1.sh: deletesred,blue,green,routerandswitchif they exist, stops at the first failure - a namespace
switchwith a bridgebr0in it, up, with no IP address - three machines,
red,blue,green, each with a cable fromveth-<name>(in the machine) tosw-<name>(inswitch), plugged intobr0and up - addresses
10.0.0.1/24(red),10.0.0.2/24(blue),10.0.0.3/24(green); every interface up,loincluded
red 10.0.0.1 blue 10.0.0.2 green 10.0.0.3
veth-red veth-blue veth-green
| | |
switch: sw-red ------------- sw-blue -------------- sw-green
\___________________ br0 ___________________/
Hint
The three machines differ only in name and number, so a loop saves typing:
for c in red blue green; do ...; done, with a counter for the last number of the address. master br0 plugs a
port into the bridge (lesson 5).
Solution
#!/bin/bash
# p2.sh: a switch (bridge br0) with red, blue and green on it (Practical 2)
set -e
for ns in red blue green router switch; do ip netns del $ns 2>/dev/null || true; done
ip netns add switch
ip -n switch link add br0 type bridge
ip -n switch link set br0 up
n=1
for c in red blue green; do
ip netns add $c
ip link add veth-$c type veth peer name sw-$c
ip link set veth-$c netns $c
ip link set sw-$c netns switch
ip -n switch link set sw-$c master br0
ip -n switch link set sw-$c up
ip -n $c addr add 10.0.0.$n/24 dev veth-$c
ip -n $c link set lo up
ip -n $c link set veth-$c up
n=$((n + 1))
done
./on bash p2.sh
./on bridge -n switch link
Three ports, each master br0 state forwarding.
Predict first: red pings blue for the first time while
tcpdumplistens in green. What does green see?
ip netns exec green timeout 6 tcpdump -n -e -c 5 -i veth-green arp or icmp & sleep 1; ip netns exec red ping -c3 10.0.0.2; wait
bridge -n switch fdb show br br0 | grep -v permanent
Why: arp or icmp leaves out the IPv6 messages new interfaces send by themselves; -e shows MAC addresses.
What you see
One frame: red’s ARP request, to ff:ff:ff:ff:ff:ff. The reply and the pings went only to blue’s port. The
forwarding database shows which port each MAC was learned on.
Task 2 · A service on blue
Add two lines to p2.sh:
- near the top, before the deletes: stop any
ncalready running in the lab (pkill -x nc), without failing when there is none. A program running in a namespace keeps it alive afterip netns del, so an old listener would linger. - at the end: start
nc -lk 8080in blue, in the background, so it keeps running after./onreturns.
Hint
pkill -x nc || true. For the service, setsid -f <command> </dev/null >/dev/null 2>&1 starts it detached from your
terminal: a plain & dies with the ./on session.
Solution
pkill -x nc || true
(after set -e), and as the last line:
setsid -f ip netns exec blue nc -lk 8080 </dev/null >/dev/null 2>&1
./on bash p2.sh
./on ip netns exec blue ss -tlnp
./on ip netns exec red nc -zv -w2 10.0.0.2 8080
./on ip netns exec green nc -zv -w2 10.0.0.2 8080
ss shows LISTEN on 0.0.0.0:8080 with users:(("nc",...)), and both say
Connection to 10.0.0.2 8080 port [tcp/http-alt] succeeded!.
Predict first: red sends
helloto the service. How many packets cross before the first one with data?
ip netns exec blue timeout 6 tcpdump -n -c 8 -i veth-blue tcp port 8080 & sleep 1; echo hello | ip netns exec red nc -N -w2 10.0.0.2 8080; wait
What you see
Three: [S], [S.], [.], the handshake. Then [P.] with length 6 (hello and a newline), blue’s [.],
and the close: [F.] from each side and a last [.]. Red’s port is a different ephemeral number each run.
Task 3 · Break it: the wrong address
Restart the service the way a hasty config change would:
pkill -x nc; setsid -f ip netns exec blue nc -lk 127.0.0.1 8080 </dev/null >/dev/null 2>&1
Red can’t connect any more. Find out why using only these, in this order:
- is blue there?
ip netns exec red ping -c1 10.0.0.2 - what kind of failure?
ip netns exec red nc -zv -w2 10.0.0.2 8080: at once, or after a wait? - what crosses the wire?
ip netns exec blue timeout 6 tcpdump -n -c 2 -i veth-blue tcp port 8080 & sleep 1; ip netns exec red nc -z -w2 10.0.0.2 8080; wait - what listens?
ip netns exec blue ss -tlnp
What each says
1 works: the network is fine. 2 fails at once: Connection refused, an answer. 3 shows the answer, [S] then
[R.]. 4 shows the cause: LISTEN on 127.0.0.1:8080, which takes connections from blue itself only.
Fix it by running your script, which starts the service the right way: ./on bash p2.sh.
Task 4 · Break it: unplugged
Now take blue’s port out of the switch, and make red forget blue’s MAC (as if it had been a while):
ip -n switch link set sw-blue nomaster
ip -n red neigh flush all
Predict first: will red’s
ncto blue say refused, timed out, or something else, and how fast?
time ip netns exec red nc -zv -w5 10.0.0.2 8080
Find where it breaks, in this order:
ip netns exec red ping -c3 10.0.0.2ip -n red neighip -n blue -br linkbridge -n switch link
What each says
nc gives No route to host after about 3 seconds. 1 says Destination Host Unreachable, from red itself. 2 shows
10.0.0.2 ... FAILED: nobody answered ARP. 3 is the trap: blue’s veth-blue is still UP with LOWER_UP. 4
lists only sw-red and sw-green: blue’s port is out of the bridge.
Put it back with ./on bash p2.sh, which rebuilds everything, the service included.
| Break | Error | How fast | Found with |
|---|---|---|---|
service on 127.0.0.1 | Connection refused | at once | ss -tlnp on blue |
| blue unplugged | No route to host | about 3 s | ip neigh, then bridge link |
Check your work
./lab check p2
All 37 checks should pass. They read the switch, its ports and the three machines, ping blue and green from red,
check that something listens on port 8080 in blue on every address, connect to it from red and green, and read
p2.sh.
Go deeper: one connection, seen from the switch
A port of the bridge is an interface like any other, so tcpdump works on it too, from inside switch. Watch
red’s side of a connection to blue on sw-red, with the MACs:
ip netns exec switch timeout 6 tcpdump -n -e -c 4 -i sw-red tcp port 8080 & sleep 1; ip netns exec red nc -z -w2 10.0.0.2 8080; wait
The frames carry red’s and blue’s MACs (ip -n red -br link, ip -n blue -br link): the bridge passes them along
without changing them. A router (Practical 1, Go deeper) rewrites them; a switch doesn’t.
Next: lesson 7 · Firewalls and NAT.
Practical 3 · Capstone: netcheck
Goal: a lab with a DNS server, a router and a web service, and
netcheck, a Bash script you write from an empty folder. It asks lesson 1’s six questions in order and names the first that fails. Then the checker breaks your lab eleven ways, and netcheck has to name every one.Time: ~90 minutes. Where: files in
~/linux-networking-zero/on your computer; network commands inside the lab container (./on). Read lesson 7 and lesson 8 first.
./lab setup p3 # installs the DNS server, dnsmasq, in netlab
Skipped a practical, or your lab is in a state you don’t trust? ./lab reset p3 (on your computer) deletes every
namespace in netlab and rebuilds what Practicals 0 to 2 built. Then run your p3.sh.
As before, commands in a bash block run inside the lab (./on opens a shell there); the ones starting with
./on or ./lab run on your computer.
Task 1 · The lab
Lesson 8’s lab, with a router in front of blue, so a route can break too. Write ~/linux-networking-zero/p3.sh:
- starts clean: for each of
red,blue,green,router,switch, stops every program running in it (ip netns pids <name>lists them), then deletes it; stops at the first failure - a switch
br0inswitch, withred(10.0.1.2/24),green(10.0.1.3/24) androuter(10.0.1.1/24) plugged in as in Practical 2:veth-<name>in the machine,sw-<name>on the bridge - a cable from
r-blueinrouter(10.0.2.1/24) toveth-blueinblue(10.0.2.2/24), as in Practical 1 - default routes: red and green via
10.0.1.1, blue via10.0.2.1; forwarding on in router - green runs lesson 8’s DNS server, answering
web.labwith10.0.2.2and listening on10.0.1.3; red’sresolv.confnames it - blue runs lesson 8’s web service on port 8080
red 10.0.1.2 green 10.0.1.3 (DNS) router 10.0.1.1 | 10.0.2.1 blue 10.0.2.2 (web :8080)
veth-red veth-green veth-router r-blue ------------- veth-blue
| | |
switch: sw-red ----- sw-green ------------- sw-router (br0)
Hint
Copy P2’s loop for the three machines on the switch, and P1’s lines for the cable. dnsmasq puts itself in the
background, so a plain ip netns exec green dnsmasq ... is enough; the web service needs setsid -f. Lesson 8’s
lab started them like this, on 10.0.0.x addresses (change them for this lab):
ip netns exec green dnsmasq --no-resolv --no-hosts --address=/web.lab/10.0.0.2 --listen-address=10.0.0.3 --bind-interfaces --pid-file=/run/dnsmasq-green.pid
setsid -f ip netns exec blue bash -c 'while true; do printf "HTTP/1.0 200 OK\r\nContent-Length: 6\r\n\r\nhello\n" | nc -l -N 8080 >/dev/null; done' </dev/null >/dev/null 2>&1
--address=/web.lab/... is the one name it answers, --listen-address and --bind-interfaces keep it on green’s
address only, and nc -l -N sends the reply and closes once the loop’s printf is done.
Solution
#!/bin/bash
# p3.sh: the capstone's lab: red, green (DNS) and router on a switch; blue (a web service) behind router
set -e
for ns in red blue green router switch; do
ip netns pids $ns 2>/dev/null | xargs -r kill # programs still running in an old namespace
ip netns del $ns 2>/dev/null || true
done
ip netns add switch
ip -n switch link add br0 type bridge
ip -n switch link set br0 up
for c in red green router; do
ip netns add $c
ip link add veth-$c type veth peer name sw-$c
ip link set veth-$c netns $c
ip link set sw-$c netns switch
ip -n switch link set sw-$c master br0
ip -n switch link set sw-$c up
ip -n $c link set lo up
ip -n $c link set veth-$c up
done
ip -n red addr add 10.0.1.2/24 dev veth-red
ip -n green addr add 10.0.1.3/24 dev veth-green
ip -n router addr add 10.0.1.1/24 dev veth-router
ip netns add blue
ip link add veth-blue type veth peer name r-blue
ip link set veth-blue netns blue
ip link set r-blue netns router
ip -n router addr add 10.0.2.1/24 dev r-blue
ip -n blue addr add 10.0.2.2/24 dev veth-blue
ip -n router link set r-blue up
ip -n blue link set lo up
ip -n blue link set veth-blue up
ip -n red route add default via 10.0.1.1
ip -n green route add default via 10.0.1.1
ip -n blue route add default via 10.0.2.1
ip netns exec router sysctl -w net.ipv4.ip_forward=1
ip netns exec green dnsmasq --no-resolv --no-hosts --address=/web.lab/10.0.2.2 \
--listen-address=10.0.1.3 --bind-interfaces --pid-file=/run/dnsmasq-green.pid
mkdir -p /etc/netns/red
rm -f /etc/netns/red/hosts # lesson 8's hosts line, if it's still there
echo "nameserver 10.0.1.3" > /etc/netns/red/resolv.conf
setsid -f ip netns exec blue bash -c 'while true; do
printf "HTTP/1.0 200 OK\r\nContent-Length: 6\r\n\r\nhello\n" | nc -l -N 8080 >/dev/null; done' </dev/null >/dev/null 2>&1
Why the kill: a program running in a namespace keeps it alive after ip netns del, so without it an old
dnsmasq or web service would keep running, unseen, in a namespace you can no longer reach.
./on bash p3.sh
./on ip netns exec red curl -sS http://web.lab:8080/
hello: everything works.
Predict first: turn forwarding off in router. Does red still get an answer for
web.lab? Doescurl?
ip netns exec router sysctl -w net.ipv4.ip_forward=0
ip netns exec red dig +short web.lab
ip netns exec red curl -sS -m5 http://web.lab:8080/
ip netns exec router sysctl -w net.ipv4.ip_forward=1
What you see
dig still answers 10.0.2.2: green is on red’s own link, so DNS needs no router. curl waits its 5 seconds and
gives up. A break leaves the questions before it working, which is why netcheck can ask them one at a time.
Task 2 · netcheck: the way there
Make an empty folder ~/linux-networking-zero/netcheck/ and write netcheck/netcheck in it (chmod +x it).
It runs in the lab, from the workspace:
./on netcheck/netcheck red web.lab 8080
The contract (the checker reads only the last line and the exit code):
| Line | When |
|---|---|
ok <what it found> | each question that passes, in order |
BROKEN <what>: <detail>, exit 1 | the first that fails; <what> is one of dns route forward arp drop reject port app, or unknown when none of them explains it |
OK ..., exit 0 | everything passed |
Netcheck sees every namespace, like an admin logged in to every machine. The first half:
- name (question 1):
getent hostsfrom the machine; if it gives nothing,BROKEN dns, withdig’sstatus:orcommunications errorline as the detail - route (question 2):
ip -n <machine> route get <address>; if it fails,BROKEN route. Note itsvia(the gateway) and itssrc(the machine’s own address) - link (question 3): a
ping -c1 -W1to the next hop answers, elseBROKEN arpwithip neigh show <hop>. When there is a gateway, find the namespace that has its address, check that it forwards (elseBROKEN forward), has a route to the address (elseBROKEN route) and gets a ping answer from it (elseBROKEN arp) - back (question 2, the way back): the namespace with the address has a route back to
src, elseBROKEN route
Hint
Two small functions save most of the typing: broken() { echo "BROKEN $*"; exit 1; }, and one that loops over
ip netns list and prints the namespace whose ip -n <ns> -br addr contains " <address>/". awk pulls a word out
of a line: awk '{for (i = 1; i < NF; i++) if ($i == "via") print $(i + 1)}'.
Solution
#!/bin/bash
# netcheck <machine> <name> <port>: from <machine>, ask lesson 1's questions in order; name the first that fails
from=$1 name=$2 port=$3
[ -n "$port" ] || { echo "usage: netcheck <machine> <name> <port>"; exit 2; }
ok() { echo "ok $*"; }
broken() { echo "BROKEN $*"; exit 1; }
owner() { # the namespace that has the address $1
for ns in $(ip netns list | awk '{print $1}'); do
ip -n $ns -br addr | grep -q " $1/" && echo $ns
done
}
answers() { # $1 pings $2 on its own link; else say why
ip netns exec $1 ping -c1 -W1 $2 >/dev/null && return
broken "arp: $1 gets no answer from $2 ($(ip -n $1 neigh show $2))"
}
# 1. name -> address
addr=$(ip netns exec $from getent hosts $name | awk '{print $1; exit}')
[ -n "$addr" ] || broken "dns: $name doesn't resolve on $from ($(ip netns exec $from dig +tries=1 +time=2 $name |
grep -o -m1 -E 'status: [A-Z]+|communications error.*'))"
ok "name $name is $addr"
# 2, 3. which way, who on the link: each hop to the machine that has the address
r=$(ip -n $from route get $addr 2>&1) || broken "route: $from has no route to $addr ($r)"
src=$(echo "$r" | awk '{for (i = 1; i < NF; i++) if ($i == "src") print $(i + 1)}')
gw=$(echo "$r" | awk '{for (i = 1; i < NF; i++) if ($i == "via") print $(i + 1)}')
if [ -n "$gw" ]; then
answers $from $gw
router=$(owner $gw)
ok "route $from sends it to $router ($gw)"
[ "$(ip netns exec $router sysctl -n net.ipv4.ip_forward)" = 1 ] ||
broken "forward: $router doesn't forward (net.ipv4.ip_forward = 0)"
r=$(ip -n $router route get $addr 2>&1) || broken "route: $router has no route to $addr ($r)"
answers $router $addr
else
answers $from $addr
fi
target=$(owner $addr)
ok "link $addr ($target) answers on its link"
r=$(ip -n $target route get $src 2>&1) || broken "route: $target has no route back to $src ($r)"
ok "back $target has a route back to $src"
./on netcheck/netcheck red web.lab 8080
ok name web.lab is 10.0.2.2
ok route red sends it to router (10.0.1.1)
ok link 10.0.2.2 (blue) answers on its link
ok back blue has a route back to 10.0.1.2
Break it. Take away blue’s way back, run netcheck, then point red at a DNS server that isn’t there:
ip -n blue route del default
netcheck/netcheck red web.lab 8080
echo "nameserver 10.0.1.9" > /etc/netns/red/resolv.conf
netcheck/netcheck red web.lab 8080
What you see
BROKEN route: blue has no route back to 10.0.1.2 (RTNETLINK answers: Network is unreachable)
From red alone, this looks like a DROP (lesson 7); netcheck finds it by asking blue. The second run stops at the first question, after the resolver’s waits (about 15 s):
BROKEN dns: web.lab doesn't resolve on red (communications error to 10.0.1.9#53: timed out)
Put the lab back with ./on bash p3.sh.
Task 3 · netcheck: let through, listening, answering
From the client, questions 4 to 6 come down to one request. Add to netcheck:
- read the packet counters of every
DROPandREJECTrule in every namespace (iptables -L -n -v -x), make one request withcurl -s -o /dev/null -m 5, and read the counters again - let through? (question 4) a counter that went up:
BROKEN droporBROKEN reject, naming the namespace (lesson 7: the rule that counts is the one catching them) - listening? (question 5)
curlexit code 7 (couldn’t connect):BROKEN port, with whatss -Htlnshows listening on that port - answers? (question 6) connected but no HTTP status:
BROKEN app; a2xxor3xxstatus:OK
Hint
curl -w '%{http_code} %{time_connect} %{errormsg}' prints the status (000 when there was none), how long the
connection took (0.000000 when it never connected) and curl’s error. diff <(echo "$before") <(echo "$after")
shows the counter lines that changed.
Solution
# 4, 5, 6. let through? listening? does the program answer? One request, and the firewall counters around it
counters() {
for ns in $(ip netns list | awk '{print $1}'); do
ip netns exec $ns iptables -L -n -v -x | awk -v ns=$ns '$3 == "DROP" || $3 == "REJECT" {print ns, $3, NR, $1}'
done
}
before=$(counters)
out=$(ip netns exec $from curl -s -o /dev/null -m 5 -w '%{http_code} %{time_connect} %{errormsg}' http://$name:$port/)
rc=$?
after=$(counters)
hit=$(diff <(echo "$before") <(echo "$after") | awk '/^>/ {print $2, $3; exit}') # e.g. "blue DROP"
if [ -n "$hit" ]; then
set -- $hit
broken "${2,,}: a $2 rule in $1 caught the packets (iptables -L -n -v)"
fi
ok "firewall no DROP or REJECT rule caught them"
if [ $rc = 7 ]; then
listen=$(ip netns exec $target ss -Htln "sport = :$port" | awk '{print $4}')
broken "port: nothing on $target listens on $addr:$port (listening: ${listen:-none})"
fi
read code connected why <<< "$out"
case "$code" in
[23]??) ok "port $target listens on $port"; echo "OK $name:$port from $from: HTTP $code" ;;
*) [ "$connected" != "0.000000" ] && broken "app: connected to $addr:$port, but no HTTP answer (curl: $why)"
broken "unknown: curl: $why" ;;
esac
${2,,} is Bash for “$2 in lower case”.
./on netcheck/netcheck red web.lab 8080
ok firewall no DROP or REJECT rule caught them
ok port blue listens on 8080
OK web.lab:8080 from red: HTTP 200
Predict first: a REJECT rule on blue makes
curlsayConnection refused, the same words as a closed port. Will netcheck sayportorreject?
ip netns exec blue iptables -I INPUT -p tcp --dport 8080 -j REJECT
netcheck/netcheck red web.lab 8080
ip netns exec blue iptables -D INPUT -p tcp --dport 8080 -j REJECT
What you see
BROKEN reject: a REJECT rule in blue caught the packets (iptables -L -n -v)
The counters are read before the exit code, so the rule is found first.
Task 4 · Let the checker break it
./lab check p3
It checks the lab as p3.sh builds it and runs netcheck (it must end with OK). Then, only in a container with
Practical 0’s --label, it breaks the lab one way at a time, runs netcheck, and undoes the break:
| Break | netcheck must say | Lesson |
|---|---|---|
red’s DNS server is 10.0.1.9; a name green doesn’t know | dns | 8 |
| red’s default route deleted; blue’s default route deleted | route | 4 |
| forwarding off in router | forward | 4 |
| blue’s cable down | arp | 5 |
| a DROP on blue (INPUT); a DROP on router (FORWARD) | drop, naming the namespace | 7 |
| a REJECT on blue | reject | 7 |
| port 8081, where nothing listens | port | 6 |
blue’s web service frozen with kill -STOP | app | 8 |
All 56 checks should pass. The frozen service is lesson 8’s point: the kernel still completes the handshake, so
curl connects, and then no answer ever comes.
A check fails? Run that break by hand (./lab’s BREAKS lists them) and read netcheck’s whole output.
./on bash p3.sh rebuilds everything.
Go deeper: where netcheck stops
netcheck reads the counters iptables -L shows. A rule written with nft in a table of its own (lesson 7, Go
deeper) isn’t among them:
ip netns exec blue nft add table inet lab
ip netns exec blue nft add chain inet lab input "{ type filter hook input priority 0; }"
ip netns exec blue nft add rule inet lab input tcp dport 8080 counter drop
ok firewall no DROP or REJECT rule caught them
BROKEN unknown: curl: Connection timed out after 5002 milliseconds
nft list table inet lab on blue shows the rule’s counter packets 5 bytes 300 drop. Reading nft list ruleset
instead of iptables -L would catch both. Take the table out with ip netns exec blue nft delete table inet lab.
A DROP for ping on blue (iptables -I INPUT -p icmp -j DROP) fools the arp step:
BROKEN arp: router gets no answer from 10.0.2.2 (10.0.2.2 dev r-blue lladdr c6:fb:96:df:3b:fe REACHABLE )
The detail gives it away: router has blue’s MAC (lladdr), so ARP worked and only the ping went unanswered. A
script names the first failure it can see; a person still reads the detail. On real machines, netcheck’s view of
every namespace becomes one ssh per hop.
Next: you’ve finished the course. The front page lists what each lesson covered.