Lesson 02 · 30 minutes
Read the addresses and routes of your machine
- List the interfaces and IP addresses of your machine
- Explain a subnet mask in CIDR form and test if an address is in a network
- Read the routing table and find the default route
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
You work in the IT team of a small company. The web server log shows requests from eight addresses. Your team lead asks: "Which of these come from our offices, which are private addresses of some other network, and which are on the internet?" The offices use the network 10.20.0.0/22. You get the eight addresses in a file, and you must sort them without guessing.
Recall
Which layer of the OSI model do MAC addresses belong to, and which layer do IP addresses belong to?
MAC addresses belong to layer 2, the data link layer, and they work on one local network only. IP addresses belong to layer 3, the network layer, and they work between networks (lesson 1).
A packet crosses a router. Which part of its headers does the router rebuild, and which part does it keep?
The router builds a new Ethernet header for the next hop, so the MAC addresses change. It keeps the IP addresses and lowers the TTL by one (lesson 1).
The idea
An interface is a connection of your machine to a network: a cable port, a Wi-Fi card, or a virtual one. Each interface has one or more IP addresses. An IPv4 address is four numbers from 0 to 255, for example 192.168.1.50. An IPv6 address is longer, in hexadecimal, for example fe80::1.
Three kinds of address matter first:
| Address | Meaning |
|---|---|
127.0.0.1 | The loopback. It always means "this machine". Traffic to it never leaves the machine. Its name is localhost. |
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 | Private ranges (RFC 1918). They are not routed on the public internet. Homes and offices reuse them. |
| Everything else | Public addresses, unique on the internet. |
A network is a block of addresses written as an address and a length, for example 192.168.1.0/24. This is CIDR notation. The number after the slash says how many bits at the start of the address are fixed. In /24, the first 24 bits (the first three numbers) are fixed and the last 8 bits are free, so the block holds 256 addresses. The subnet mask is the same idea written as a number: /24 is 255.255.255.0. Two addresses are on the same network when their fixed bits are the same.
The routing table tells the kernel where to send a packet. It picks the most specific matching entry. If nothing else matches, it uses the default route: the address of a gateway (usually your router) that forwards the packet onward.
- Program → Routing table: send to 192.168.2.15
- Routing table → Gateway: no specific route, use the default
- Gateway → Remote host: forward it to its network
Worked example
1. Go to your lab folder
cd (change directory) moves you into a directory, and pwd (print working directory) shows where you are. You made this folder in the set-up lesson.
cd ~/krlab/networking
pwd/home/you/krlab/networking2. List your interfaces and addresses
ip is the tool of Linux for the network settings of the machine. ip addr lists the addresses (addr is short for address). The option -4 shows IPv4 only, and -br (brief) gives one short line for each interface.
ip -4 -br addrlo UNKNOWN 127.0.0.1/8
ens1f0 UP 192.168.1.50/24 The output is shortened. Your names and numbers will differ: eth0, enp3s0 or wlan0 are common. Find the interface that is UP and has a private address. Note its address and its prefix length (here /24).
3. Look at the loopback
ip addr show lo shows the full detail of one interface, here the interface named lo.
ip -4 addr show lo1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft foreverLOOPBACK is the interface type. The /8 means that the whole block 127.0.0.0/8 belongs to this machine, not only 127.0.0.1.
4. Ping yourself
ping sends a small test packet to an address and waits for the answer. The option -c 2 (count) sends two packets and stops. This test needs no network at all.
ping -c 2 127.0.0.1PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.039 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.043 ms
--- 127.0.0.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1064ms
rtt min/avg/max/mdev = 0.039/0.041/0.043/0.002 msThe time is a fraction of a millisecond because the packet never leaves your machine.
5. Read the routing table
ip route prints the routing table.
ip routedefault via 192.168.1.1 dev ens1f0 proto static
192.168.1.0/24 dev ens1f0 proto kernel scope link src 192.168.1.50 Read the second line first: to reach any address in 192.168.1.0/24, send the packet out of ens1f0 directly. The first line is the default route. proto says who added the line: kernel for the network of an interface, dhcp for a gateway from DHCP (lesson 6), static for one added by hand. scope link marks a network that is reachable directly. src is the address that the machine writes as the sender when it uses this route. Your table may have more lines, for example for a VPN or for containers.
6. Ask which route one address would use
ip route get asks the kernel which route it would use for one address. It only reads the table and sends nothing, so it works offline.
ip route get 1.1.1.11.1.1.1 via 192.168.1.1 dev ens1f0 src 192.168.1.50 uid 1000
cache The kernel chose the default route (via the gateway) and the source address 192.168.1.50. Now ask for an address on your own network, for example your neighbour 192.168.1.20. The answer has no via, because no gateway is needed.
7. Test an address against a network with Python
Python has the module ipaddress for this work. python3 -c runs the text that follows it as a small program, and import ipaddress as i loads the module under the short name i. in tests if an address is inside a network. Use your own address and prefix from step 2.
python3 -c "import ipaddress as i; print(i.ip_address('192.168.1.50') in i.ip_network('192.168.1.0/24'))"
python3 -c "import ipaddress as i; print(i.ip_address('192.168.2.15') in i.ip_network('192.168.1.0/24'))"True
FalseThe module also describes a network and classifies an address. With -c " and a quote that stays open, you can write the program on several lines:
python3 -c "
import ipaddress as i
n = i.ip_network('192.168.1.0/24')
print(n.netmask, n.num_addresses, n.broadcast_address)
print(i.ip_address('10.5.5.5').is_private, i.ip_address('8.8.8.8').is_private)
w = i.ip_network('172.16.8.0/22')
print(w.num_addresses, w.broadcast_address)
"255.255.255.0 256 192.168.1.255
True False
1024 172.16.11.255The broadcast address is the last address of a network. is_private is true for the private ranges. A /22 fixes 22 bits, so only the last 10 bits are free. That is 1,024 addresses, and the third number runs over four values (8 to 11).
Your turn
Do the task of your team lead. There are no steps here: use what the worked example showed, on the data below.
Save these eight lines in ~/krlab/networking/clients.txt. They are the addresses from the log.
clients.txt
10.20.0.15
10.20.3.200
10.20.4.1
172.16.9.9
172.32.0.1
192.168.50.7
8.8.4.4
1.1.1.1The offices use the network 10.20.0.0/22. Sort each address into one of three groups: inside the offices, private but elsewhere, or public. Write a short Python program that reads the file and does the sorting, so that you do not count by eye. Then find out which interface your kernel would use to reach 127.0.0.1.
When your answers pass, find one address that surprised you and say why. Look at 172.32.0.1 first.
A model sorter
import ipaddress
office = ipaddress.ip_network("10.20.0.0/22")
groups = {"inside": 0, "private elsewhere": 0, "public": 0}
for line in open("clients.txt"):
address = ipaddress.ip_address(line.strip())
if address in office:
groups["inside"] += 1
elif address.is_private:
groups["private elsewhere"] += 1
else:
groups["public"] += 1
print(groups)
print(office[-1])It prints {'inside': 2, 'private elsewhere': 3, 'public': 3} and 10.20.3.255. The order of the tests matters: the office network is also private, so it is tested first.
Check yourself
Your machine is 192.168.1.50/24. Can it reach 192.168.2.40 directly, without the gateway?
No. The fixed part of a /24 is the first three numbers, 192.168.1. The address 192.168.2.40 has a different third number, so it is on another network. The kernel sends the packet to the default gateway.
A server log shows a request from 172.20.4.9. Is it from the internet?
No. 172.20.4.9 is inside 172.16.0.0/12, a private range. The request came from inside a private network, or from a proxy or NAT device that sits in front of the real client. Check the range carefully: 172.32.0.1 is public, because the private block ends at 172.31.255.255.
Why does ping to 127.0.0.1 work when the network cable is out?
The loopback interface is inside the kernel. The packet goes from your machine to your machine and never uses a cable or a card. A successful loopback ping proves only that the network stack is running, not that the real network works.
What does the kernel do with a packet when two routes match?
It uses the most specific one, the one with the longest prefix. The default route (/0) matches every address, so it has the lowest priority and is used last.
Field notes
- Do not write your own address checks with string tests such as
startswith("10."). Useipaddress(ornet/netipin Go). It handles IPv6, mapped addresses and odd forms. ipaddresshasis_private,is_loopback,is_link_localandis_global. For a rule such as "the server must never fetch an internal address" (a defence against server-side request forgery), checkis_globalon the address after the name is resolved, not on the text of the URL.is_privatein Python also covers the loopback and the documentation ranges, so it is wider than RFC 1918: state which definition your check uses.100.64.0.0/10is not private in the RFC 1918 sense but is not public either: it is shared address space for carrier-grade NAT, and some VPN products use it.169.254.0.0/16is link-local; a host with such an address failed to get one by DHCP. Know these ranges when you triage logs.- A route can change the path of traffic without a firewall rule. An attacker or a misconfigured VPN that adds a more specific route can send your traffic elsewhere. Save
ip routeoutput as a baseline and compare it during an incident. ipreplaced the olderifconfigandroute. On a hardened server onlyipmay be present, so learn it first.