SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 18

Cybersecurity Fundamentals · Lesson 18 of 90 · 20 min

IP addressing, subnets, routing and NAT

IPv4IPv6CIDR notationsubnet maskprivate address ranges (RFC 1918)loopbackroutingdefault gatewayNATPATARPICMPping and traceroute (concept)DHCP

These are the notes for Cybersecurity Fundamentals (defensive), episode 18. Last episode put an IP address on every packet. Today we open that address up and invent, one problem at a time: IPv4 and its octets, CIDR notation and the subnet mask, subnets, IPv6, the private address ranges (RFC 1918), loopback, routing, the routing table and the default gateway, NAT and PAT, ARP, DHCP, ICMP, ping and traceroute, and finally the IPv6 security considerations every defender must know. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Ravi, his office, his housing society and all the devices are made up. Every address in the demos is either private (RFC 1918) or reserved for documentation (RFC 5737 / RFC 3849), so nothing here touches a real network. Every code sample runs with Python 3.13 using only the standard library; outputs are real, copied from actual runs. In tracebacks, long file paths are shortened to just the file name. Traceroute is simulated in plain Python: only ever ping or trace networks you are authorised to test.

The problems you'll solve

Problem Idea it teaches
Give every device an address IP address, host, IPv4, octet, bit
"Is this IP in our office range?" gives wrong answers An IP is one 32-bit number; compare as numbers
Where does the network part end? CIDR notation, prefix length, subnet mask, network and broadcast address, subnets
4.29 billion addresses was not enough IANA exhaustion, private ranges (RFC 1918), loopback, public addresses, IPv6
How does a packet find its way? Router, routing, routing table, next hop, default route, default gateway, longest prefix match
Forty devices, one public address NAT, port, PAT
How do I reach a neighbour on my LAN? ARP, ARP cache, ARP spoofing
Who hands out addresses? DHCP, lease, rogue DHCP, DHCP starvation
Something broke: where? ICMP, ping, TTL, traceroute
IPv6 is switched on Dual stack, no NAT, rogue Router Advertisements, privacy addresses

Problem 1: an address for every device

A letter reaches you because of two pieces of information: the PIN code (which area) and the house number (which door in that area). The post office reads the area first, and only at the end the door.

Computers do exactly the same. An IP address (Internet Protocol address) is a number that identifies one device on a network, and it has two parts:

  • the network part: which network (like the PIN code), and
  • the host part: which device on that network (like the house number).

A host is any device on a network that has an address: your phone, a laptop, a printer, a server.

Every packet (a small chunk of data sent across a network, from episode 17) carries two IP addresses: the source (sender) and the destination (receiver).

The version most of the world still uses is IPv4, defined in RFC 791 by Jon Postel in September 1981. An RFC ("Request for Comments") is a numbered document that publishes Internet standards and best practices.

IPv4: four numbers that are really one number

An IPv4 address looks like 192.168.1.9. This style is called dotted decimal: four numbers separated by dots.

  • A bit is a single 0 or 1.
  • Each of the four numbers is an octet: 8 bits. Eight bits can count from 00000000 (0) to 11111111 (255), so no part of an IPv4 address is ever above 255.
  • Four octets make 32 bits. To a computer, an IPv4 address is really one 32-bit number. The dots are only for humans.
Octet 192 168 1 9
Bits 11000000 10101000 00000001 00001001

Demo 1: the obvious way fails (comparing IPs as text)

Ravi runs IT for a small office. Addresses from 192.168.1.2 to 192.168.1.200 count as "inside". The obvious check compares the addresses as strings (text):

# is a guest's IP inside our office range?
office_low = "192.168.1.2"
office_high = "192.168.1.200"

for ip in ["192.168.1.50", "192.168.1.9",
           "192.168.1.100"]:
    inside = office_low <= ip <= office_high
    print(ip, "inside office range?", inside)

Output:

192.168.1.50 inside office range? False
192.168.1.9 inside office range? False
192.168.1.100 inside office range? False

All three are inside, and all three answers are wrong. There is no error message, which makes it worse.

Why: text is compared one character at a time, like words in a dictionary. In "50" versus "200", the first characters are 5 and 2; 5 is bigger, so the text "...50" sorts after "...200". A firewall rule or a log filter written this way quietly lets the wrong addresses in, or keeps the right ones out.

The fix: treat an IP address as the number it really is.

Demo 2: an IP is one number

Python's standard-library module ipaddress turns text into real address and network objects that compare as numbers.

import ipaddress

ip = ipaddress.ip_address("192.168.1.9")
print("as one number:", int(ip))
print("in binary:", format(int(ip), "032b"))

net = ipaddress.ip_network("192.168.1.0/24")
print("network:", net)
print("subnet mask:", net.netmask)
print("addresses:", net.num_addresses)
print("first host:", next(net.hosts()))
print("broadcast:", net.broadcast_address)
for s in ["192.168.1.9", "192.168.1.200", "192.168.2.9"]:
    print(s, "in net?", ipaddress.ip_address(s) in net)

Output:

as one number: 3232235785
in binary: 11000000101010000000000100001001
network: 192.168.1.0/24
subnet mask: 255.255.255.0
addresses: 256
first host: 192.168.1.1
broadcast: 192.168.1.255
192.168.1.9 in net? True
192.168.1.200 in net? True
192.168.2.9 in net? False

Now the answers are correct. 192.168.1.9 is the number 3,232,235,785 (192×256³ + 168×256² + 1×256 + 9). Even plain ipaddress.ip_address("192.168.1.50") <= ipaddress.ip_address("192.168.1.200") gives True, as it should.

Problem 2: CIDR notation and the subnet mask

What do /24 and 255.255.255.0 mean?

CIDR notation and the prefix length

192.168.1.0/24 means: the first 24 bits are the network part, and the remaining 8 bits are the host part.

  • The number after the slash is the prefix length: how many leading bits name the network.
  • Writing an address, a slash and a prefix length is CIDR notation (Classless Inter-Domain Routing).
Network part (24 bits) Host part (8 bits)
192.168.1.9/24 192.168.1 .9

History. Before CIDR, networks came in only three fixed sizes called classes (Class A, B and C), so an organisation that needed 300 addresses had to take a block of 65,536 and waste most of it. CIDR, specified today in RFC 4632 (August 2006, BCP 122), replaced the fixed classes with prefixes of any length, to conserve IPv4 space and slow the growth of routing tables.

The subnet mask

The subnet mask says the same thing as the prefix length, but as an address-shaped number: ones for every network bit, zeros for every host bit.

/24  =  11111111.11111111.11111111.00000000  =  255.255.255.0
/26  =  11111111.11111111.11111111.11000000  =  255.255.255.192
/12  =  11111111.11110000.00000000.00000000  =  255.240.0.0

A computer finds the network part by doing a bitwise AND of the address and the mask (keeping only the bits where the mask has a 1).

Size, network address and broadcast address

  • A network with prefix /p holds 2^(32 − p) addresses. /24 → 2⁸ = 256.
  • The first address (host bits all 0, e.g. 192.168.1.0) is the network address: the name of the whole network.
  • The last address (host bits all 1, e.g. 192.168.1.255) is the broadcast address: a message sent to it goes to every host on that network at once.
  • So a /24 has 254 usable host addresses (.1 to .254).

Subnets and subnetting

Splitting one network into smaller networks is subnetting; each smaller network is a subnet. Every extra bit of prefix halves the size. Subnets matter for security: hosts in different subnets must go through a router or firewall to talk, so you can separate guests from cameras from servers (more in episode 24, network segmentation).

Demo 3: masks, sizes, subnets and a typo

import ipaddress

for cidr in ["10.0.0.0/8", "172.16.0.0/12",
             "192.168.0.0/16", "192.168.1.0/24",
             "192.168.1.0/26"]:
    n = ipaddress.ip_network(cidr)
    print(f"{cidr:15} mask {n.netmask!s:16}",
          f"{n.num_addresses:>10,}")

office = ipaddress.ip_network("192.168.1.0/24")
for sub in office.subnets(new_prefix=26):
    print("subnet:", sub)

try:
    ipaddress.ip_network("192.168.1.10/24")   # oops?
except ValueError as e:
    print("ValueError:", e)

Output:

10.0.0.0/8      mask 255.0.0.0        16,777,216
172.16.0.0/12   mask 255.240.0.0       1,048,576
192.168.0.0/16  mask 255.255.0.0          65,536
192.168.1.0/24  mask 255.255.255.0           256
192.168.1.0/26  mask 255.255.255.192          64
subnet: 192.168.1.0/26
subnet: 192.168.1.64/26
subnet: 192.168.1.128/26
subnet: 192.168.1.192/26
ValueError: 192.168.1.10/24 has host bits set

Without the try/except, Python stops with a traceback that ends in the same line: ValueError: 192.168.1.10/24 has host bits set.

Ravi's four /26 subnets (64 addresses each) could be: staff .0/26, guests .64/26, cameras .128/26, servers .192/26.

The typo: a network must be named by its network address, with every host bit 0. 192.168.1.10/24 has host bits set (the .10). Ravi meant 192.168.1.0/24. Python refusing is a good thing: a sloppy firewall rule might silently mean something else. If you really want "the network that contains this address", say so explicitly: ipaddress.ip_network("192.168.1.10/24", strict=False) gives 192.168.1.0/24.

Quick reference

Prefix Mask Addresses Usable hosts
/8 255.0.0.0 16,777,216 16,777,214
/12 255.240.0.0 1,048,576 1,048,574
/16 255.255.0.0 65,536 65,534
/22 255.255.252.0 1,024 1,022
/24 255.255.255.0 256 254
/26 255.255.255.192 64 62
/27 255.255.255.224 32 30
/30 255.255.255.252 4 2
/32 255.255.255.255 1 a single host

Problem 3: we ran out of addresses

32 bits give 2³² = 4,294,967,296 IPv4 addresses, about 4.29 billion. That sounded endless in 1981. Then came billions of phones, laptops, smart TVs and cameras.

IANA, the Internet Assigned Numbers Authority, sits at the top of the address handout: it gives big blocks to five Regional Internet Registries (RIRs), which give smaller blocks to ISPs and organisations. On 3 February 2011, IANA allocated its last five /8 blocks (one to each RIR), and its IPv4 free pool was fully depleted.

The Internet needed two fixes: reuse addresses, and a bigger address.

Fix one: private ranges, loopback and public addresses

Every housing society has a flat A-101. Inside the society that is enough, but a courier from outside can't deliver to "A-101" alone. RFC 1918 (February 1996, BCP 5) set aside three private address ranges that anyone may reuse inside their own network. They are never routed on the public Internet.

RFC 1918 block Range Size
10.0.0.0/8 10.0.0.0 to 10.255.255.255 16,777,216
172.16.0.0/12 172.16.0.0 to 172.31.255.255 1,048,576
192.168.0.0/16 192.168.0.0 to 192.168.255.255 65,536

Watch out for the middle one: 172.16.0.0/12 runs to 172.31.255.255, so 172.20.0.5 is private but 172.32.0.1 is public.

A note stuck on your own fridge never leaves the house. Loopback addresses always mean "this same machine": 127.0.0.1 (the whole block 127.0.0.0/8 is reserved for loopback) and ::1 in IPv6. Programs use loopback to talk to other programs on the same computer, for example a local web server at http://127.0.0.1:8000. Traffic to loopback never leaves the device.

Everything else is a public address: unique on the whole Internet, like a full postal address. Your home router gets one from your ISP (Internet Service Provider, the company that connects you to the Internet).

Other special blocks you'll see in logs (RFC 6890, April 2013):

Block Meaning
169.254.0.0/16 IPv4 link-local: a device gives itself one when DHCP fails
fe80::/10 IPv6 link-local: valid only on the local link
fc00::/7 IPv6 unique-local (IPv6's version of private addresses)
192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32 Documentation only: used in examples like this one

Fix two: IPv6

IPv6, Internet Protocol version 6, specified today in RFC 8200 (July 2017, STD 86), "increases the IP address size from 32 bits to 128 bits".

  • It is written in hexadecimal (base 16: digits 0 to 9 and letters a to f), in eight groups of four hex digits, separated by colons: 2001:0db8:0000:0000:0000:0000:0000:0001.
  • Leading zeros in a group may be dropped (0db8 → db8).
  • One run of all-zero groups may be replaced by :: (only once, or the address would be ambiguous).
  • So that address is written 2001:db8::1.

Most networks run IPv4 and IPv6 side by side today (dual stack, see the security section).

Demo 4: address space, IPv6 and special addresses

import ipaddress

print("all IPv4 addresses:", f"{2**32:,}")
print("all IPv6 addresses:", f"{2**128:.3e}")

v6 = ipaddress.ip_address(
    "2001:0db8:0000:0000:0000:0000:0000:0001")
print("compressed:", v6.compressed)
print("exploded:  ", v6.exploded)

for s in ["10.4.2.7", "172.20.0.5", "192.168.0.10",
          "8.8.8.8", "127.0.0.1", "::1"]:
    a = ipaddress.ip_address(s)
    print(f"{s:12} private={a.is_private}",
          f"loopback={a.is_loopback}")

Output:

all IPv4 addresses: 4,294,967,296
all IPv6 addresses: 3.403e+38
compressed: 2001:db8::1
exploded:   2001:0db8:0000:0000:0000:0000:0000:0001
10.4.2.7     private=True loopback=False
172.20.0.5   private=True loopback=False
192.168.0.10 private=True loopback=False
8.8.8.8      private=False loopback=False
127.0.0.1    private=True loopback=True
::1          private=True loopback=True

IPv6 has about 3.4 × 10³⁸ addresses (exactly 340,282,366,920,938,463,463,374,607,431,768,211,456, a 39-digit number). Python's is_private is broader than RFC 1918: it is True for any address that is not globally reachable, which includes loopback.

Problem 4: routing and the default gateway

A packet now has a destination address. How does it get there?

Think of a railway junction like Itarsi: trains arrive and switch to the right line.

  • A router is a device that joins networks and forwards each packet one step closer to its destination. Your home Wi-Fi box contains one.
  • Routing is choosing that path.
  • The junction's chart says "for Mumbai, line 2". A router's routing table lists destination networks and, for each, the next hop: the next router to hand the packet to (or "deliver directly" if the destination is on a network the router is connected to).
  • "Anywhere else: main line." The default route, written 0.0.0.0/0 (prefix length 0, so it matches every address), catches everything not listed.
  • On your laptop, the default route points to your home router. That router is your default gateway: the door out of your local network. Packets for your own subnet are delivered directly; everything else goes to the gateway.

Demo 5: first match fails, longest prefix match fixes it

import ipaddress as ip
routes = [                      # destination -> next hop
    ("0.0.0.0/0",      "ISP (default)"),
    ("10.0.0.0/8",     "office VPN"),
    ("10.20.0.0/16",   "Mumbai branch"),
    ("192.168.1.0/24", "local LAN"),
]

def first_match(dst):
    for net, hop in routes:         # obvious: top to bottom
        if ip.ip_address(dst) in ip.ip_network(net):
            return hop
def longest_match(dst):
    hits = [(ip.ip_network(n), h) for n, h in routes
            if ip.ip_address(dst) in ip.ip_network(n)]
    return max(hits, key=lambda x: x[0].prefixlen)[1]
for d in ["10.20.5.9", "10.1.1.1", "192.168.1.7", "8.8.8.8"]:
    print(f"{d:12} first: {first_match(d):14}",
          f"longest: {longest_match(d)}")

Output:

10.20.5.9    first: ISP (default)  longest: Mumbai branch
10.1.1.1     first: ISP (default)  longest: office VPN
192.168.1.7  first: ISP (default)  longest: local LAN
8.8.8.8      first: ISP (default)  longest: ISP (default)

Why first-match failed: the default route matches every address, so if it is checked first it always wins, and traffic meant for the private Mumbai branch would leave over the open Internet.

The fix real routers use: longest prefix match. Of all the routes that match, choose the most specific one, the one with the longest prefix. 10.20.5.9 matches /0, /8 and /16; /16 wins.

Security angle: routing decides where your data physically goes. A wrong or injected route can send traffic through an attacker. Inside a LAN that's ARP and rogue DHCP (below); across the Internet it's BGP hijacking (episode 23).

Problem 5: NAT and PAT

Ravi's home has forty devices, but his ISP gives him one public address.

Picture an old housing society with one outside phone line and forty flats. When flat B-204 calls the pharmacy, the guard places the call from the society's number and writes in his register "this call belongs to B-204". When the pharmacy calls back, he checks the register and puts it through. A caller nobody asked for finds no entry, and reaches no one.

  • NAT (Network Address Translation): the router rewrites the private source address of outgoing packets into its one public address, remembers the mapping in a translation table, and rewrites replies back to the private address.
  • A port is a number (0 to 65535) that labels one conversation on an address (ports are covered fully in episode 19).
  • PAT (Port Address Translation), also called NAT overload or NAPT: many private devices share one public address, and the router tells their conversations apart by giving each its own public port. This is what almost every home router does.

Demo 6: a toy PAT table

PUBLIC_IP = "203.0.113.5"     # the ONE address from the ISP
nat = {}                       # public port -> inside pair
next_port = 40000

def go_out(src_ip, src_port):
    global next_port
    pub = (PUBLIC_IP, next_port)  # rewrite the return address
    nat[next_port] = (src_ip, src_port)
    next_port += 1
    return pub

def come_back(dst_port):
    return nat.get(dst_port, "no entry: DROP")

print("phone  ->", go_out("192.168.1.7", 51000))
print("laptop ->", go_out("192.168.1.9", 51000))
print("TV     ->", go_out("192.168.1.12", 443))
print("reply to 40001 goes to", come_back(40001))
print("stranger hits 40099 ->", come_back(40099))

Output:

phone  -> ('203.0.113.5', 40000)
laptop -> ('203.0.113.5', 40001)
TV     -> ('203.0.113.5', 40002)
reply to 40001 goes to ('192.168.1.9', 51000)
stranger hits 40099 -> no entry: DROP

Phone and laptop both used private port 51000, yet they are told apart, because each got its own public port.

NAT is not a firewall

Dropping unrequested traffic is a nice side effect, but NAT's job is translation, not filtering:

  • A port forward (a permanent "send port 8080 to the camera" rule) exposes that device to the whole Internet.
  • A device that is already infected calls out to the attacker first, which creates a table entry, so replies come straight in.
  • IPv6 usually has no NAT at all, so every device can have a globally reachable address.

Real protection is a firewall with a default-deny inbound policy (episode 24).

Problem 6: ARP, finding a neighbour

Inside one local network (a LAN, local area network), Ethernet cables and Wi-Fi deliver frames by MAC address, the hardware address burned into each network card (episode 17), not by IP address. So when Ravi's laptop wants to send a packet to its gateway 192.168.1.1, it first needs the gateway's MAC address.

A teacher knows a roll number but not the face, so she asks the class: "Who is roll number 12?" One student raises a hand.

  • ARP (Address Resolution Protocol), RFC 826 by David C. Plummer, November 1982: a device broadcasts "who has 192.168.1.1?" to everyone on the LAN, and the owner replies "I do, my MAC is aa:aa:aa:00:00:01".
  • The answer is stored in an ARP cache: a short-lived memory of IP-to-MAC pairs, so the question isn't asked for every packet.

The weak spot: ARP has no authentication. RFC 826's receiver updates its table from the packets it receives, without any proof of who sent them. Any device can answer, even when nobody asked (an unsolicited reply). A liar who claims to be the gateway receives everyone's traffic and can pass it on, reading or changing it. This is ARP spoofing (also ARP poisoning): a classic man-in-the-middle (an attacker sitting between two parties) on a local network.

Demo 7: a cache that believes a liar, and a check that doesn't

arp_cache = {}                 # IP -> MAC, learned on the LAN
def hear_reply(ip, mac):       # ARP has NO authentication:
    arp_cache[ip] = mac        # whoever answers is believed

hear_reply("192.168.1.1", "aa:aa:aa:00:00:01")  # real router
print("gateway is", arp_cache["192.168.1.1"])
hear_reply("192.168.1.1", "ee:ee:ee:66:66:66")  # a liar
print("gateway is", arp_cache["192.168.1.1"])
# defence idea: check replies against a trusted table
trusted = {"192.168.1.1": "aa:aa:aa:00:00:01"}
def safe_hear(ip, mac):
    if ip in trusted and trusted[ip] != mac:
        print("ALERT: ARP reply for", ip, "from", mac)
        return
    arp_cache[ip] = mac
safe_hear("192.168.1.1", "aa:aa:aa:00:00:01")
safe_hear("192.168.1.1", "ee:ee:ee:66:66:66")
print("gateway is", arp_cache["192.168.1.1"])

Output:

gateway is aa:aa:aa:00:00:01
gateway is ee:ee:ee:66:66:66
ALERT: ARP reply for 192.168.1.1 from ee:ee:ee:66:66:66
gateway is aa:aa:aa:00:00:01

The plain cache was poisoned. With the trusted table, the real reply restores the correct MAC and the lie raises an alert. Real defences: dynamic ARP inspection on managed switches (checks ARP against a trusted IP-to-MAC table built by DHCP snooping), static ARP entries for critical hosts, network monitoring for MAC changes, and encryption (TLS) so that even intercepted traffic can't be read. More in episode 23.

Problem 7: DHCP, addresses on demand

If every device typed in its own address, two would sooner or later pick the same one (an address conflict), like two cars fighting for one parking slot.

So the society secretary keeps a register: "slot 7 is yours for a month."

  • DHCP (Dynamic Host Configuration Protocol), RFC 2131 by R. Droms, March 1997, "provides configuration parameters to Internet hosts".
  • A new device and a DHCP server (usually inside your home router) exchange four messages, remembered as DORA: 1. Discover: the client broadcasts "is there a DHCP server?" 2. Offer: a server offers an address and settings. 3. Request: the client asks for the offered address. 4. Ack: the server confirms (acknowledges).
  • The client receives an IP address, the subnet mask, the default gateway, the DNS server (episode 20) and more.
  • The address is given for a fixed period called a lease. The client renews it before it expires; if it doesn't, the address returns to the pool (the range of addresses the server hands out).

The weak spots:

  • Rogue DHCP server. RFC 2131's own Security Considerations section says DHCP "in its current form is quite insecure" and "Unauthorized DHCP servers may be easily set up." A rogue server can name itself as the default gateway or DNS server and quietly sit in the middle of traffic. Sometimes it's an accident (someone plugs in a home router at work).
  • DHCP starvation. Requesting addresses with many fake MAC addresses until the pool is empty, so real devices get none.
  • Defence: DHCP snooping on switches (only the port where the real server lives may send Offers and Acks), port security limiting MACs per port, and monitoring. More in episode 23.

Demo 8: a toy DHCP server

import ipaddress
net = ipaddress.ip_network("192.168.1.0/28")
pool = list(net.hosts())     # 14 hosts; drop router:
pool.remove(ipaddress.ip_address("192.168.1.1"))
leases = {}                      # MAC -> address

def dhcp(mac):                # Discover/Offer/Request/Ack
    if mac not in leases:
        if not pool:
            return "no free address (pool empty)"
        leases[mac] = pool.pop(0)
    return f"{leases[mac]}  gateway 192.168.1.1  lease 24h"

print("phone :", dhcp("aa:01"))
print("laptop:", dhcp("aa:02"))
print("phone again:", dhcp("aa:01"))
for i in range(3, 16):
    last = dhcp(f"aa:{i:02}")
print("15th device:", last)

Output:

phone : 192.168.1.2  gateway 192.168.1.1  lease 24h
laptop: 192.168.1.3  gateway 192.168.1.1  lease 24h
phone again: 192.168.1.2  gateway 192.168.1.1  lease 24h
15th device: no free address (pool empty)

A /28 has 16 addresses, 14 usable; minus the router leaves 13 for clients. The phone keeps .2 because its lease is on record. The 14th and 15th devices get nothing: the pool is empty, exactly what DHCP starvation forces on purpose.

Problem 8: ICMP, ping and traceroute

Something's broken. Is the server down, or the path to it? The post office stamps a returned letter "address not found".

  • ICMP (Internet Control Message Protocol), RFC 792 by Jon Postel, September 1981. Its purpose: "to provide feedback about problems in the communication environment".
ICMP type Name Meaning
8 Echo (request) "Are you there?"
0 Echo Reply "Yes, I'm here"
3 Destination Unreachable "Can't deliver this"
11 Time Exceeded "This packet's TTL ran out"
  • ping sends an ICMP Echo Request and waits for an Echo Reply, like ringing a doorbell: it tells you the host answered and the round-trip time (how long there and back took).
  • Every IP packet carries a TTL (time to live): a hop counter, not a clock. Each router subtracts 1; a router that finds the TTL at zero must discard the packet, and it sends an ICMP Time Exceeded message back to the sender. TTL stops packets circling forever in a routing loop.
  • traceroute (tracert on Windows) uses that rule on purpose: it sends packets with TTL 1, then 2, then 3, and so on. Each router on the path, in turn, discards one and reports back with Time Exceeded, revealing itself, until the destination itself answers.

Demo 9: traceroute, simulated

# a SIMULATED path: no real network is touched
path = ["home router 192.168.1.1", "ISP Pune 10.9.0.1",
        "ISP Mumbai 10.9.8.1", "server 198.51.100.20"]

def send(ttl):
    for hop in path:
        if hop.startswith("server"):
            return f"ICMP Echo Reply from {hop}"
        ttl -= 1                  # every router subtracts 1
        if ttl == 0:              # dead: report back
            return f"ICMP Time Exceeded from {hop}"

for ttl in range(1, 5):           # traceroute's trick
    print(f"TTL={ttl}:", send(ttl))

Output:

TTL=1: ICMP Time Exceeded from home router 192.168.1.1
TTL=2: ICMP Time Exceeded from ISP Pune 10.9.0.1
TTL=3: ICMP Time Exceeded from ISP Mumbai 10.9.8.1
TTL=4: ICMP Echo Reply from server 198.51.100.20

Defender's view of ICMP. It is useful feedback for troubleshooting, but it also helps outsiders map a network (which hosts answer, what the path looks like). So firewalls usually rate-limit ICMP and allow only the useful types at the edge rather than blocking all of it: some ICMP messages are needed for networks to work properly, and IPv6 cannot work without ICMPv6 (it uses it to find neighbours and routers). Only ever ping or traceroute networks you are authorised to test.

IPv6 security considerations

Switching on IPv6 changes the security picture in four main ways:

Consideration What goes wrong Defence
Dual stack (IPv4 and IPv6 running at the same time) Teams lock down IPv4 and forget IPv6, which operating systems often enable by default; an attacker uses the forgotten one Every IPv4 firewall rule, log source and alert needs an IPv6 twin; or disable IPv6 where it's truly unused
No NAT Plenty of addresses means devices can be globally reachable A stateful firewall that denies unrequested inbound traffic by default
Rogue Router Advertisements IPv6 routers announce themselves with Router Advertisements (RAs); a fake RA, accidental or malicious, makes a device everyone's gateway (RFC 6104, February 2011) RA-Guard on switches (only trusted ports may send RAs), monitoring
Tracking by address An address that never changes lets websites follow one device across networks Temporary privacy addresses that change over time (RFC 8981, February 2021)

Also: don't block ICMPv6 blindly (IPv6 needs it), and make sure your logging and threat-intel tools understand IPv6 addresses and :: compression.

The next problem

IP got the packet to Ravi's laptop. But the laptop runs a browser, a chat app, music and updates at the same time. Which program is this packet for? And did the earlier packets arrive, and in order? That's the job of ports, TCP and UDP, and the three-way handshake: next episode.

The whole chain

  1. Every device needs an address → IPv4: network part + host part.
  2. Comparing addresses as text lied → an IP is one 32-bit number.
  3. Where's the split? → CIDR, prefix length, subnet mask, subnets.
  4. We ran out → private ranges (RFC 1918), loopback, IPv6.
  5. Find the way → routing, longest prefix match, default gateway.
  6. Forty devices, one address → NAT, PAT (not a firewall).
  7. Neighbours and addresses → ARP and DHCP, which both trust anyone.
  8. What broke? → ICMP, ping, TTL, traceroute.

Common mistakes (and what they print)

Mistake What you get Why Fix
"192.168.1.50" <= "192.168.1.200" False (wrong answer, no error) Text compares character by character ipaddress.ip_address(...), in network
ipaddress.ip_network("192.168.1.10/24") ValueError: 192.168.1.10/24 has host bits set A network is named by its network address 192.168.1.0/24, or strict=False on purpose
ipaddress.ip_address("192.168.1.300") ValueError: '192.168.1.300' does not appear to be an IPv4 or IPv6 address An octet can't exceed 255 Validate input; catch ValueError
ipaddress.ip_network("192.168.1.0/33") ValueError: '192.168.1.0/33' does not appear to be an IPv4 or IPv6 network IPv4 prefixes go from /0 to /32 Use a valid prefix
ip_address("10.0.0.1") < ip_address("::1") TypeError: 10.0.0.1 and ::1 are not of the same version IPv4 and IPv6 can't be ordered together Compare within one version, or sort by (version, address)
First-match routing with the default on top All traffic goes to the ISP 0.0.0.0/0 matches everything Longest prefix match
Thinking 172.32.0.1 is private A public address treated as internal RFC 1918's middle block ends at 172.31.255.255 Use ipaddress / the table, not memory
"We have NAT, so we're safe" Port forwards and IPv6 hosts exposed NAT translates, it doesn't filter Stateful firewall, default deny, IPv4 and IPv6
Blocking all ICMP Broken path-MTU discovery, IPv6 stops working Some ICMP is required Rate-limit and allow the needed types

Mini project: Ravi's address triage tool

Security logs are full of addresses. This tool reads a list and tells you, for each entry, whether it's invalid, loopback, one of Ravi's office subnets, private, special-purpose, or public (the ones worth checking against threat intelligence, the lists of known bad addresses).

import ipaddress as ip

OFFICE = {                          # Ravi's four /26 subnets
    "staff":   ip.ip_network("192.168.1.0/26"),
    "guests":  ip.ip_network("192.168.1.64/26"),
    "cameras": ip.ip_network("192.168.1.128/26"),
    "servers": ip.ip_network("192.168.1.192/26"),
}
RFC1918 = [ip.ip_network(n) for n in
           ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")]

def classify(text):
    try:
        a = ip.ip_address(text.strip())
    except ValueError as e:
        return f"INVALID ({e})"
    if a.is_loopback:
        return "loopback (this machine)"
    for name, net in OFFICE.items():
        if a in net:
            return f"office subnet '{name}' ({net})"
    for net in RFC1918:
        if a in net:
            return f"private, RFC 1918 block {net}"
    if a.is_private:
        return "special-purpose (not public)"
    return "PUBLIC: check it in your threat intel"

log = ["192.168.1.20", "192.168.1.70", "192.168.1.200",
       "10.20.5.9", "172.31.0.4", "127.0.0.1", "::1",
       "203.0.113.7", "8.8.8.8", "192.168.1.300", "fe80::1"]
for entry in log:
    print(f"{entry:15} -> {classify(entry)}")

Output:

192.168.1.20    -> office subnet 'staff' (192.168.1.0/26)
192.168.1.70    -> office subnet 'guests' (192.168.1.64/26)
192.168.1.200   -> office subnet 'servers' (192.168.1.192/26)
10.20.5.9       -> private, RFC 1918 block 10.0.0.0/8
172.31.0.4      -> private, RFC 1918 block 172.16.0.0/12
127.0.0.1       -> loopback (this machine)
::1             -> loopback (this machine)
203.0.113.7     -> special-purpose (not public)
8.8.8.8         -> PUBLIC: check it in your threat intel
192.168.1.300   -> INVALID ('192.168.1.300' does not appear to be an IPv4 or IPv6 address)
fe80::1         -> special-purpose (not public)

Ideas to extend it: read addresses from a file, count how many come from each subnet, and flag any guest address that appears in the servers logs (that should never happen if segmentation works).

Practice

1. Homework: split 10.0.0.0/24 into 8 subnets. Print each with its usable host count and broadcast address.

Solution

8 = 2³, so borrow 3 bits: /24 + 3 = /27.

import ipaddress
net = ipaddress.ip_network("10.0.0.0/24")
for sub in net.subnets(new_prefix=27):    # 8 = 2^3 -> 24+3
    hosts = sub.num_addresses - 2
    print(sub, "hosts:", hosts, "broadcast:", sub.broadcast_address)

Output:

10.0.0.0/27 hosts: 30 broadcast: 10.0.0.31
10.0.0.32/27 hosts: 30 broadcast: 10.0.0.63
10.0.0.64/27 hosts: 30 broadcast: 10.0.0.95
10.0.0.96/27 hosts: 30 broadcast: 10.0.0.127
10.0.0.128/27 hosts: 30 broadcast: 10.0.0.159
10.0.0.160/27 hosts: 30 broadcast: 10.0.0.191
10.0.0.192/27 hosts: 30 broadcast: 10.0.0.223
10.0.0.224/27 hosts: 30 broadcast: 10.0.0.255

2. Homework: add 172.16.5.0/24 → lab to the routing demo. Where do 172.16.5.40, 172.16.6.1 and 10.20.0.1 go?

Solution
import ipaddress as ip
routes = [("0.0.0.0/0", "ISP (default)"), ("10.0.0.0/8", "office VPN"),
          ("10.20.0.0/16", "Mumbai branch"), ("192.168.1.0/24", "local LAN"),
          ("172.16.5.0/24", "lab")]
def longest_match(dst):
    hits = [(ip.ip_network(n), h) for n, h in routes
            if ip.ip_address(dst) in ip.ip_network(n)]
    return max(hits, key=lambda x: x[0].prefixlen)[1]
for d in ["172.16.5.40", "172.16.6.1", "10.20.0.1"]:
    print(d, "->", longest_match(d))

Output:

172.16.5.40 -> lab
172.16.6.1 -> ISP (default)
10.20.0.1 -> Mumbai branch

172.16.6.1 is outside the /24, so only the default matches. (It's an RFC 1918 address, so in real life it should never reach the ISP: many networks add a route or firewall rule that drops private destinations at the edge.)

3. Homework: make the NAT table forget old entries. Real routers delete a mapping after a timeout.

Solution
PUBLIC_IP, TIMEOUT = "203.0.113.5", 60      # seconds
nat, next_port = {}, 40000

def go_out(src, now):
    global next_port
    nat[next_port] = (src, now)              # remember WHEN
    next_port += 1
    return (PUBLIC_IP, next_port - 1)

def come_back(port, now):
    entry = nat.get(port)
    if entry is None or now - entry[1] > TIMEOUT:
        nat.pop(port, None)                  # forget stale ones
        return "no entry: DROP"
    return entry[0]

print(go_out(("192.168.1.9", 51000), now=0))
print("reply at t=10:", come_back(40000, now=10))
print("reply at t=500:", come_back(40000, now=500))
print("table now:", nat)

Output:

('203.0.113.5', 40000)
reply at t=10: ('192.168.1.9', 51000)
reply at t=500: no entry: DROP
table now: {}

4. Usable hosts for any prefix. Write usable_hosts(prefix).

Solution
def usable_hosts(prefix):
    total = 2 ** (32 - prefix)
    return total - 2 if prefix <= 30 else total
for p in (8, 16, 22, 24, 27, 30, 31, 32):
    print(f"/{p}: {usable_hosts(p):,} usable")

Output:

/8: 16,777,214 usable
/16: 65,534 usable
/22: 1,022 usable
/24: 254 usable
/27: 30 usable
/30: 2 usable
/31: 2 usable
/32: 1 usable

/31 and /32 are special cases: a /31 is used for a two-device point-to-point link (no network or broadcast address is needed), and a /32 names exactly one host, as in a firewall rule for a single server.

5. Same LAN or not? A laptop has 172.20.13.77/20. Find its network, mask and broadcast, and decide whether 172.20.15.1 and 172.20.16.1 are on the same LAN (delivered directly) or must go via the gateway.

Solution
import ipaddress
iface = ipaddress.ip_interface("172.20.13.77/20")
print("address:  ", iface.ip)
print("network:  ", iface.network)
print("mask:     ", iface.netmask)
print("broadcast:", iface.network.broadcast_address)
print("same LAN as 172.20.15.1?",
      ipaddress.ip_address("172.20.15.1") in iface.network)
print("same LAN as 172.20.16.1?",
      ipaddress.ip_address("172.20.16.1") in iface.network)

Output:

address:   172.20.13.77
network:   172.20.0.0/20
mask:      255.255.240.0
broadcast: 172.20.15.255
same LAN as 172.20.15.1? True
same LAN as 172.20.16.1? False

ip_interface holds an address with its prefix (what a network card is configured with), unlike ip_network, which must have host bits zero.

6. Explain in your own words: why is NAT not a firewall?

Answer

NAT rewrites addresses so many devices can share one; dropping unrequested inbound packets is only a side effect of having no table entry. Port forwards, infected devices that connect out first, and IPv6 (usually no NAT) all bypass it. A firewall applies an explicit policy (default deny, allow only what's needed) to both IPv4 and IPv6.

Quick quiz

Ravi gives the cameras 192.168.1.64/27. How many addresses can he give to cameras?

A. 32 B. 30 C. 27 D. 64

Answer

B. /27 leaves 32 − 27 = 5 host bits: 2⁵ = 32 addresses. Minus the network address (.64) and the broadcast address (.95) = 30 usable hosts.

Interview questions

  1. What is the difference between IPv4 and IPv6? IPv4 addresses are 32 bits (about 4.3 billion), written in dotted decimal; IPv6 addresses are 128 bits, written in hex groups separated by colons. IPv6 removes the need for NAT, uses ICMPv6 for neighbour discovery, and has its own security considerations.
  2. What does /24 mean, and what is the subnet mask? The first 24 bits are the network part; the mask is 24 ones then zeros, 255.255.255.0. It holds 256 addresses, 254 usable.
  3. List the RFC 1918 ranges. 10.0.0.0/8, 172.16.0.0/12 (to 172.31.255.255), 192.168.0.0/16. They're not routed on the public Internet.
  4. What is a default gateway? The router a host sends packets to when the destination isn't on its own subnet; it's the target of the default route 0.0.0.0/0.
  5. How does a router choose between overlapping routes? Longest prefix match: the most specific matching route wins.
  6. What's the difference between NAT and PAT? Is NAT a security control? NAT translates addresses; PAT also translates ports so many hosts share one public IP. NAT is not a firewall; filtering needs explicit firewall policy.
  7. How does ARP spoofing work, and how do you defend against it? ARP has no authentication, so an attacker sends forged replies mapping the gateway's IP to their MAC and becomes a man in the middle. Defend with dynamic ARP inspection, static entries for critical hosts, monitoring and end-to-end encryption.
  8. What is a rogue DHCP server and how is it stopped? An unauthorised DHCP server handing out a malicious gateway or DNS server; stopped with DHCP snooping that trusts only the legitimate server's port.
  9. How does traceroute work? It sends packets with increasing TTL; each router that decrements TTL to zero discards the packet and returns ICMP Time Exceeded, revealing the path.
  10. Name three IPv6 security considerations. Dual stack (secure both, IPv6 often on by default), no NAT (devices globally reachable, need a stateful firewall), rogue Router Advertisements (RA-Guard), plus privacy addresses and not blocking ICMPv6 blindly.

Glossary

Term Meaning in plain words Example
IP address A number identifying a device on a network, with a network part and a host part 192.168.1.9
Host Any device on a network that has an address A phone, a printer
Packet A small chunk of data sent across a network, carrying source and destination addresses One piece of a web page
RFC "Request for Comments": a numbered document publishing Internet standards RFC 791 (IPv4)
IPv4 Internet Protocol version 4: 32-bit addresses (RFC 791, 1981) 10.4.2.7
Bit A single 0 or 1 1
Octet 8 bits; one of the four numbers in an IPv4 address (0 to 255) 168
Dotted decimal Writing IPv4 as four decimal octets with dots 192.168.1.9
Network part The leading bits naming the network (like a PIN code) 192.168.1 in a /24
Host part The remaining bits naming the device (like a house number) .9
Prefix length How many leading bits are the network part /24
CIDR notation Classless Inter-Domain Routing: address + slash + prefix length (RFC 4632) 192.168.1.0/24
Address classes The old fixed network sizes (A, B, C) that CIDR replaced Class C = /24
Subnet mask The prefix as an address-shaped number: ones for network bits 255.255.255.0
Network address First address of a network, host bits all 0; names the network 192.168.1.0
Broadcast address Last address of a network, host bits all 1; reaches every host on it 192.168.1.255
Subnet / subnetting A smaller network carved out of a bigger one / the act of splitting Four /26s from a /24
ipaddress module Python's standard library for addresses and networks ip_network("10.0.0.0/8")
IANA Internet Assigned Numbers Authority: top of the address handout Free pool empty 3 Feb 2011
RIR Regional Internet Registry: hands addresses to ISPs in a region APNIC for Asia-Pacific
ISP Internet Service Provider: connects you to the Internet Gives your router a public IP
Private address ranges (RFC 1918) Blocks anyone can reuse internally, never routed on the Internet 10/8, 172.16/12, 192.168/16
Public address Globally unique, reachable on the Internet 8.8.8.8
Loopback An address meaning "this same machine"; traffic never leaves it 127.0.0.1, ::1
Link-local An address valid only on the local link 169.254.x.x, fe80::/10
Documentation addresses Blocks reserved for examples 203.0.113.0/24, 2001:db8::/32
IPv6 Internet Protocol version 6: 128-bit addresses (RFC 8200) 2001:db8::1
Hexadecimal Base 16: digits 0 to 9 and a to f db8
:: (IPv6) Shorthand for one run of all-zero groups 2001:db8::1
Router A device that joins networks and forwards packets towards their destination Your home Wi-Fi box
Routing Choosing the path a packet takes Itarsi junction
Routing table A router's list of destination networks and next hops Demo 5
Next hop The next router a packet is handed to "Mumbai branch"
Default route 0.0.0.0/0: matches every address; the catch-all "Anywhere else: main line"
Default gateway The router a host uses for any destination off its own subnet 192.168.1.1
Longest prefix match Choosing the most specific matching route /16 beats /8 and /0
NAT Network Address Translation: rewriting private addresses into a public one and back Home router
Translation table NAT's record of which inside device owns which conversation nat dict in Demo 6
Port A number (0 to 65535) labelling one conversation on an address (episode 19) 40001
PAT Port Address Translation (NAT overload): many devices share one IP, told apart by port Phone, laptop, TV on 203.0.113.5
Port forward A permanent NAT rule sending one public port to an inside device Port 8080 → camera
Firewall A device or program that allows or blocks traffic by policy (episode 24) Default deny inbound
LAN Local area network: devices on one local network Ravi's office Wi-Fi
MAC address The hardware address of a network card, used to deliver frames on a LAN (episode 17) aa:aa:aa:00:00:01
Frame The unit a LAN (Ethernet/Wi-Fi) delivers, addressed by MAC (episode 17) Carries an IP packet
ARP Address Resolution Protocol: finds the MAC for an IP on the LAN (RFC 826, 1982) "Who has 192.168.1.1?"
ARP cache A short-lived table of learned IP-to-MAC pairs arp_cache in Demo 7
ARP spoofing / poisoning Forged ARP replies that make victims send traffic to the attacker The prankster shouting "me!"
Man-in-the-middle (MITM) An attacker secretly sitting between two parties, relaying traffic A fake gateway
Dynamic ARP inspection A switch feature that drops ARP replies that don't match trusted bindings Demo 7's trusted table
DHCP Dynamic Host Configuration Protocol: hands out addresses and settings (RFC 2131, 1997) Your phone joining Wi-Fi
DORA Discover, Offer, Request, Ack: DHCP's four messages Demo 8
Lease The time a DHCP address is lent for 24 hours
Address pool The range of addresses a DHCP server can hand out .2 to .14
Address conflict Two devices using the same IP address Two cars, one slot
Rogue DHCP server An unauthorised DHCP server giving out false settings A fake secretary
DHCP starvation Exhausting a DHCP pool with fake requests 15th device gets nothing
DHCP snooping A switch feature that only trusts DHCP replies from the real server's port Blocks rogue servers
ICMP Internet Control Message Protocol: feedback about delivery problems (RFC 792, 1981) Destination Unreachable
ICMPv6 ICMP for IPv6; also finds neighbours and routers, so IPv6 needs it Router Advertisement
ping A tool sending ICMP Echo Requests and timing the Echo Replies "Are you home?"
Round-trip time Time for a packet to go there and back Shown by ping
TTL Time to live: a hop counter; each router subtracts 1, at 0 the packet is dropped TTL=3 dies at hop 3
traceroute A tool that maps the path by sending increasing TTLs Demo 9
Network mapping Learning which hosts exist and how they connect; attackers do it first Why ICMP is limited
Dual stack IPv4 and IPv6 running at the same time Most networks today
Router Advertisement (RA) An IPv6 message in which a router announces itself and the network prefix Rogue RAs (RFC 6104)
RA-Guard A switch feature that only allows RAs from trusted ports Stops rogue RAs
Privacy (temporary) addresses IPv6 addresses that change over time to stop tracking (RFC 8981) A laptop's daily new address
IPv6 security considerations What changes for defenders when IPv6 is on: dual stack, no NAT, RAs, tracking Every v4 rule needs a v6 twin
Threat intelligence Information about known malicious addresses, domains and behaviour Checking a public IP from a log

Summary

  • An IP address has a network part and a host part. IPv4 is 32 bits, written as four octets (0 to 255), but it's really one number: compare addresses as numbers (ipaddress), never as text.
  • CIDR notation (/24) gives the prefix length; the subnet mask (255.255.255.0) says the same thing. A /p has 2^(32−p) addresses; the first is the network address, the last the broadcast. Subnetting splits networks, which lets firewalls separate them.
  • IANA's IPv4 pool ran out on 3 February 2011. Fixes: RFC 1918 private ranges (10/8, 172.16/12, 192.168/16), loopback (127.0.0.1, ::1), and IPv6 (128 bits, 2001:db8::1).
  • Routers forward packets using a routing table and longest prefix match; the default route 0.0.0.0/0 points to the default gateway.
  • NAT/PAT lets many devices share one public address. NAT is not a firewall.
  • ARP maps IP to MAC and DHCP hands out addresses; both trust anyone, so defend with dynamic ARP inspection and DHCP snooping.
  • ICMP carries feedback; ping uses Echo, traceroute uses TTL and Time Exceeded. Limit ICMP, don't blindly block it.
  • IPv6 security: secure both stacks, use a stateful firewall (no NAT), guard against rogue RAs, use privacy addresses.

Next episode: TCP, UDP and the handshake: ports, the three-way handshake, TCP flags, SYN floods and SYN cookies, and how defenders spot port scans.

Sources: RFC 791, Internet Protocol (J. Postel, Sep 1981; via ipfyi.com); RFC 1918, Address Allocation for Private Internets (Feb 1996); RFC 4632, CIDR (Aug 2006); ARIN, "The IANA IPv4 Address Free Pool is Now Depleted" (3 Feb 2011); RFC 8200, IPv6 Specification (Jul 2017); RFC 6890, Special-Purpose IP Address Registries (Apr 2013); RFC 826, ARP (D. Plummer, Nov 1982); RFC 792, ICMP (J. Postel, Sep 1981); RFC 2131, DHCP (R. Droms, Mar 1997); RFC 6104, Rogue IPv6 Router Advertisement Problem Statement (Feb 2011); RFC 8981, Temporary Address Extensions for SLAAC (Feb 2021). Code outputs from Python 3.13. Fetched 30 Oct 2026.