Computer Networks Module 7 – IPv4 addressing, subnetting and NAT
IPv4 addresses, masks and CIDR notation
How a 32-bit IPv4 address splits into network and host bits, with subnet masks, CIDR prefixes, network and broadcast addresses and the special ranges.
What you will learn
- Convert IPv4 addresses between dotted-decimal, binary, hexadecimal and integer forms
- Find the network address, broadcast address and host range for any prefix length
- Explain why classful addressing gave way to CIDR
- Recognise private, shared (CGNAT), loopback, link-local, documentation and multicast ranges
Before you start
What you’ll learn · Before you start
What you will learn
- Convert IPv4 addresses between dotted-decimal, binary, hexadecimal and integer forms
- Find the network address, broadcast address and host range for any prefix length
- Explain why classful addressing gave way to CIDR
- Recognise private, shared (CGNAT), loopback, link-local, documentation and multicast ranges
Before you start
On this page
An IPv4 address is a 32-bit number that identifies one network interface. People write it as four decimal numbers
from 0 to 255 separated by dots, such as 10.20.30.40. Every address has two parts: the first bits say which network
it is on, and the remaining bits identify an address within that stated block. An interface can have more than
one address, and translation can let devices share one external address. CIDR prefix: The explicit length of the leading address bits that identify an IP address block. says where the split falls:
10.20.30.40/20 means the first 20 bits are the network part. A subnet mask states the same boundary as a 32-bit
pattern of ones followed by zeros, so /20 is the mask 255.255.240.0. Once you know the split, everything else
follows: the network address (all host bits 0), the broadcast address (all host bits 1), the usable host addresses
between them and how many there are. This lesson works each step by hand, runs it in Python, and maps the address
blocks that are reserved for special uses.
Four notations encode the same 32-bit address
Dotted decimal is only a convenient way to write a number. Each of the four parts is one octet (8 bits), and the four octets read one after another form a single 32-bit integer: the original Internet Protocol specification, RFC 791, defines an address as “four octets (32 bits)”. Binary is what masks work on, hexadecimal shows up in packet captures and code, and the integer form appears in databases and some programming interfaces.
# One IPv4 address written four ways: dotted decimal, binary, hexadecimal and one integer.
import ipaddress
address = ipaddress.IPv4Address("10.20.30.40")
octets = [int(part) for part in str(address).split(".")]
print("dotted :", address)
print("binary :", ".".join(f"{o:08b}" for o in octets))
print("hex :", "0x" + "".join(f"{o:02x}" for o in octets))
print("integer:", int(address))
# The integer is the four octets read as one base-256 number.
value = octets[0] * 256**3 + octets[1] * 256**2 + octets[2] * 256 + octets[3]
print("by hand:", value, value == int(address))
print("back :", ipaddress.IPv4Address(value)) Output
dotted : 10.20.30.40 binary : 00001010.00010100.00011110.00101000 hex : 0x0a141e28 integer: 169090600 by hand: 169090600 True back : 10.20.30.40
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 four_forms.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Python 3.14 · main.py
octets = [10, 20, 30, 40]
value = 0
for octet in octets:
value = value * 256 + octet
print("dotted :", ".".join(map(str, octets)))
print("binary :", ".".join(f"{octet:08b}" for octet in octets))
print("hex :", "0x" + "".join(f"{octet:02x}" for octet in octets))
print("integer:", value)
by_hand = sum(octet * 256 ** (3 - i) for i, octet in enumerate(octets))
print("by hand:", by_hand, by_hand == value)
back = ".".join(str((value >> shift) & 255) for shift in [24, 16, 8, 0])
print("back :", back) Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py
JavaScript Node 24 · main.mjs
const octets = [10, 20, 30, 40];
let value = 0;
for (const octet of octets) value = value * 256 + octet;
console.log(`dotted : ${octets.join(".")}`);
console.log(`binary : ${octets.map((o) => o.toString(2).padStart(8, "0")).join(".")}`);
console.log(`hex : 0x${octets.map((o) => o.toString(16).padStart(2, "0")).join("")}`);
console.log(`integer: ${value}`);
const byHand = octets.reduce((sum, o, i) => sum + o * 256 ** (3 - i), 0);
console.log(`by hand: ${byHand} ${byHand === value ? "True" : "False"}`);
const back = [24, 16, 8, 0].map((shift) => Math.floor(value / 2 ** shift) % 256).join(".");
console.log(`back : ${back}`); Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs
Java 25 LTS · Main.java
public class Main {
public static void main(String[] args) {
int[] octets = {10, 20, 30, 40};
long value = 0;
for (int octet : octets) value = value * 256 + octet;
var dotted = new StringBuilder();
var binary = new StringBuilder();
var hex = new StringBuilder("0x");
for (int octet : octets) {
if (dotted.length() > 0) {
dotted.append('.');
binary.append('.');
}
dotted.append(octet);
String bits = Integer.toBinaryString(octet);
binary.append("0".repeat(8 - bits.length())).append(bits);
String digits = Integer.toHexString(octet);
if (digits.length() < 2) hex.append('0');
hex.append(digits);
}
System.out.println("dotted : " + dotted);
System.out.println("binary : " + binary);
System.out.println("hex : " + hex);
System.out.println("integer: " + value);
long byHand = 0;
for (int i = 0; i < 4; i++) byHand += ((long) octets[i]) << (8 * (3 - i));
System.out.println("by hand: " + byHand + " " + (byHand == value ? "True" : "False"));
var back = new StringBuilder();
for (int shift : new int[] {24, 16, 8, 0}) {
if (back.length() > 0) back.append('.');
back.append((value >> shift) & 255);
}
System.out.println("back : " + back);
}
} Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java
C++23 · main.cpp
#include <array>
#include <cstdint>
#include <format>
#include <print>
#include <string>
int main() {
const std::array<std::uint64_t, 4> octets = {10, 20, 30, 40};
std::uint64_t value = 0;
for (const auto octet : octets)
value = value * 256 + octet;
std::string dotted, binary, hex = "0x";
for (const auto octet : octets) {
if (!dotted.empty()) {
dotted += ".";
binary += ".";
}
dotted += std::to_string(octet);
binary += std::format("{:08b}", octet);
hex += std::format("{:02x}", octet);
}
std::println("dotted : {}", dotted);
std::println("binary : {}", binary);
std::println("hex : {}", hex);
std::println("integer: {}", value);
std::uint64_t byHand = 0;
for (int i = 0; i < 4; i++)
byHand += octets[i] << (8 * (3 - i));
std::println("by hand: {} {}", byHand, byHand == value ? "True" : "False");
std::string back;
for (const auto shift : {24, 16, 8, 0}) {
if (!back.empty())
back += ".";
back += std::to_string((value >> shift) & 255);
}
std::println("back : {}", back);
} Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main
C# 14 · .NET 10 · app.cs
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
int[] octets = [10, 20, 30, 40]; long value = 0;
foreach (int octet in octets) value = value * 256 + octet;
Console.WriteLine($"dotted : {string.Join(".", octets)}");
var binary = octets.Select(o => Convert.ToString(o, 2).PadLeft(8, '0'));
Console.WriteLine($"binary : {string.Join(".", binary)}");
Console.WriteLine($"hex : 0x{string.Concat(octets.Select(o => o.ToString("x2")))}");
Console.WriteLine($"integer: {value}");
long byHand = 0; for (int i = 0; i < 4; i++) byHand += (long)octets[i] << (8 * (3 - i));
Console.WriteLine($"by hand: {byHand} {byHand == value}");
var back = new[] { 24, 16, 8, 0 }.Select(shift => (value >> shift) & 255);
Console.WriteLine($"back : {string.Join(".", back)}"); Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs
C23 · main.c
#include <stdint.h>
#include <stdio.h>
int main(void) {
const uint32_t octets[] = {10, 20, 30, 40};
uint32_t value = 0;
for (int i = 0; i < 4; i++)
value = value * 256 + octets[i];
printf("dotted : %u.%u.%u.%u\n", octets[0], octets[1], octets[2], octets[3]);
printf("binary : ");
for (int i = 0; i < 4; i++) {
if (i)
putchar('.');
for (int bit = 7; bit >= 0; bit--)
putchar((octets[i] >> bit) & 1 ? '1' : '0');
}
printf("\nhex : 0x");
for (int i = 0; i < 4; i++)
printf("%02x", octets[i]);
printf("\ninteger: %u\n", value);
uint32_t byHand = 0;
for (int i = 0; i < 4; i++)
byHand += octets[i] << (8 * (3 - i));
printf("by hand: %u %s\n", byHand, byHand == value ? "True" : "False");
printf("back : ");
for (int i = 0; i < 4; i++)
printf("%s%u", i ? "." : "", value >> (8 * (3 - i)) & 255);
putchar('\n');
return 0;
} Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main
PHP 8.5 · main.php
<?php
declare(strict_types=1);
$octets = [10, 20, 30, 40];
$value = array_reduce($octets, static fn(int $sum, int $octet): int => $sum * 256 + $octet, 0);
echo 'dotted : ' . implode('.', $octets) . "\n";
$binary = array_map(static fn(int $o): string => sprintf('%08b', $o), $octets);
echo 'binary : ' . implode('.', $binary) . "\n";
$hex = array_map(static fn(int $o): string => sprintf('%02x', $o), $octets);
echo 'hex : 0x' . implode('', $hex) . "\n";
echo 'integer: ' . $value . "\n";
$byHand = 0;
foreach ($octets as $index => $octet) {
$byHand += $octet << (8 * (3 - $index));
}
echo 'by hand: ' . $byHand . ' ' . ($byHand === $value ? 'True' : 'False') . "\n";
$back = array_map(static fn(int $shift): int => ($value >> $shift) & 255, [24,16,8,0]);
echo 'back : ' . implode('.', $back) . "\n"; Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php
Rust 1.99 · main.rs
fn main() {
let octets = [10u64, 20, 30, 40];
let value = octets.iter().fold(0, |sum, &o| sum * 256 + o);
println!(
"dotted : {}",
octets
.iter()
.map(u64::to_string)
.collect::<Vec<_>>()
.join(".")
);
println!(
"binary : {}",
octets
.iter()
.map(|o| format!("{o:08b}"))
.collect::<Vec<_>>()
.join(".")
);
println!(
"hex : 0x{}",
octets
.iter()
.map(|o| format!("{o:02x}"))
.collect::<String>()
);
println!("integer: {value}");
let by_hand: u64 = octets
.iter()
.enumerate()
.map(|(i, &o)| o << (8 * (3 - i)))
.sum();
println!(
"by hand: {by_hand} {}",
if by_hand == value { "True" } else { "False" }
);
let back = [24, 16, 8, 0]
.iter()
.map(|&s| ((value >> s) & 255).to_string())
.collect::<Vec<_>>()
.join(".");
println!("back : {back}");
} Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main
TypeScript 6.0 · main.ts
const octets = [10, 20, 30, 40];
let value = 0;
for (const octet of octets) value = value * 256 + octet;
console.log(`dotted : ${octets.join(".")}`);
console.log(`binary : ${octets.map((o) => o.toString(2).padStart(8, "0")).join(".")}`);
console.log(`hex : 0x${octets.map((o) => o.toString(16).padStart(2, "0")).join("")}`);
console.log(`integer: ${value}`);
const byHand = octets.reduce((sum, o, i) => sum + o * 256 ** (3 - i), 0);
console.log(`by hand: ${byHand} ${byHand === value ? "True" : "False"}`);
const back = [24, 16, 8, 0].map((shift) => Math.floor(value / 2 ** shift) % 256).join(".");
console.log(`back : ${back}`); Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts
Go 1.27 · main.go
package main
import (
"fmt"
"strings"
)
func main() {
octets := []uint64{10, 20, 30, 40}
value := uint64(0)
for _, octet := range octets {
value = value*256 + octet
}
dotted, binary, hex := []string{}, []string{}, []string{}
for _, octet := range octets {
dotted = append(dotted, fmt.Sprint(octet))
binary = append(binary, fmt.Sprintf("%08b", octet))
hex = append(hex, fmt.Sprintf("%02x", octet))
}
fmt.Println("dotted :", strings.Join(dotted, "."))
fmt.Println("binary :", strings.Join(binary, "."))
fmt.Println("hex :", "0x"+strings.Join(hex, ""))
fmt.Println("integer:", value)
byHand := uint64(0)
for i, octet := range octets {
byHand += octet << uint(8*(3-i))
}
truth := "False"
if byHand == value {
truth = "True"
}
fmt.Println("by hand:", byHand, truth)
back := []string{}
for _, shift := range []uint{24, 16, 8, 0} {
back = append(back, fmt.Sprint(value>>shift&255))
}
fmt.Println("back :", strings.Join(back, "."))
} Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go
Swift 6.4 · main.swift
let octets: [UInt64] = [10, 20, 30, 40]
let value = octets.reduce(UInt64(0)) { $0 * 256 + $1 }
print("dotted : \(octets.map{String($0)}.joined(separator:"."))")
let binary = octets.map {
let s = String($0, radix: 2)
return String(repeating: "0", count: 8 - s.count) + s
}
print("binary : \(binary.joined(separator:"."))")
let hex = octets.map { String($0 + 256, radix: 16).dropFirst() }.joined()
print("hex : 0x\(hex)")
print("integer: \(value)")
let byHand = octets.enumerated().reduce(UInt64(0)) { $0 + ($1.element << (8 * (3 - $1.offset))) }
print("by hand: \(byHand) \(byHand==value ? "True":"False")")
let back = [24, 16, 8, 0].map { String(value >> $0 & 255) }.joined(separator: ".")
print("back : \(back)") Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main
Ruby 4.0 · main.rb
# frozen_string_literal: true
octets = [10, 20, 30, 40]
value = octets.reduce(0) { |sum, octet| sum * 256 + octet }
puts "dotted : #{octets.join('.')}"
puts "binary : #{octets.map { |octet| format('%08b', octet) }.join('.')}"
puts "hex : 0x#{octets.map { |octet| format('%02x', octet) }.join}"
puts "integer: #{value}"
by_hand = octets.each_with_index.sum { |octet, index| octet << (8 * (3 - index)) }
puts "by hand: #{by_hand} #{by_hand == value ? 'True' : 'False'}"
back = [24, 16, 8, 0].map { |shift| (value >> shift) & 255 }.join('.')
puts "back : #{back}" Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb
Kotlin 2.4 · Main.kt
fun main() {
val octets = listOf(10L, 20L, 30L, 40L)
val value = octets.fold(0L) { sum, octet -> sum * 256 + octet }
println("dotted : ${octets.joinToString(".")}")
println("binary : ${octets.joinToString(".") { it.toString(2).padStart(8,'0') }}")
println("hex : 0x${octets.joinToString("") { it.toString(16).padStart(2,'0') }}")
println("integer: $value")
val byHand = octets.mapIndexed { i, octet -> octet shl (8 * (3 - i)) }.sum()
println("by hand: $byHand ${if (byHand == value) "True" else "False"}")
val back = listOf(24, 16, 8, 0).joinToString(".") { ((value shr it) and 255).toString() }
println("back : $back")
} Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar
Dart 3.13 · main.dart
void main() {
final octets = [10, 20, 30, 40];
final value = octets.fold(0, (sum, octet) => sum * 256 + octet);
print('dotted : ${octets.join('.')}');
print(
'binary : ${octets.map((o) => o.toRadixString(2).padLeft(8, '0')).join('.')}',
);
print(
'hex : 0x${octets.map((o) => o.toRadixString(16).padLeft(2, '0')).join()}',
);
print('integer: $value');
var byHand = 0;
for (var i = 0; i < 4; i++) byHand += octets[i] << (8 * (3 - i));
print('by hand: $byHand ${byHand == value ? 'True' : 'False'}');
final back = [24, 16, 8, 0].map((shift) => (value >> shift) & 255).join('.');
print('back : $back');
} Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart
What every language printed
dotted : 10.20.30.40 binary : 00001010.00010100.00011110.00101000 hex : 0x0a141e28 integer: 169090600 by hand: 169090600 True back : 10.20.30.40
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 10 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 151 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 3 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 8 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads PHP (about 4.3 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 21 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 720 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 182 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 11 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
- Binary: every octet is padded to 8 digits, so 20 is
00010100. Dropping the leading zeros of an octet is an easy slip in hand calculations, and it puts every later bit in the wrong place. - Hexadecimal: two hex digits per octet (
0a 14 1e 28), since one hex digit is exactly 4 bits. - Integer: the octets are the digits of a base-256 number, so the value is 10 × 256³ + 20 × 256² + 30 × 256 + 40, which is 169,090,600.
Trace 10.20.30.40 through its dotted, binary, hexadecimal and integer representations.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- Start with the four original octets 10, 20, 30 and 40. Each contributes eight bits, giving one 32-bit address.
- Pack the octets as 10 × 256^3 + 20 × 256^2 + 30 × 256 + 40 = 169,090,600. Each octet keeps its eight-bit position.
- The same value is 00001010.00010100.00011110.00101000 in binary and 0a141e28 in hexadecimal. Changing notation preserves the address value.
Checkpoint
Check: Four notations encode the same 32-bit address
One strict parsed value must drive an owned address policy
Older parsers accept other spellings too. The POSIX rules for inet_addr(), which the C function inet_aton()
follows, allow fewer than four parts and let the last part fill all the remaining bytes, so 127.1 means
127.0.0.1. They also read a
part that starts with 0x as hexadecimal and a part that starts with 0 as octal. Browsers read the host of a URL
in the same lenient way, under the IPv4 parser of the WHATWG URL Standard. Python’s ipaddress module refuses all of
these forms, and since Python 3.9.5 it treats a leading zero as an error so that nothing is read as octal by
surprise:
# The strict parser of the ipaddress module against the C library's inet_aton(), which still
# accepts the old shorthand forms: fewer than four parts, hexadecimal (0x) and octal (a leading 0).
import ipaddress
import socket
print(f"{'text':<12}{'ipaddress':<11}inet_aton")
for text in ["127.0.0.1", "127.1", "0x7f.1", "2130706433", "0177.0.0.1", "010.1.2.3"]:
try:
strict = str(ipaddress.ip_address(text))
except ValueError:
strict = "rejected"
legacy = socket.inet_ntoa(socket.inet_aton(text))
print(f"{text:<12}{strict:<11}{legacy}") Output
text ipaddress inet_aton 127.0.0.1 127.0.0.1 127.0.0.1 127.1 rejected 127.0.0.1 0x7f.1 rejected 127.0.0.1 2130706433 rejected 127.0.0.1 0177.0.0.1 rejected 127.0.0.1 010.1.2.3 rejected 8.1.2.3
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 lenient_parsers.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
The last line is the dangerous one. A person reads 010.1.2.3 as 10.1.2.3, while inet_aton() reads it as
8.1.2.3. When two parts of a system parse addresses differently, a check in one part, such as a rule that refuses
internal addresses, can be dodged by writing the address in a form that only the other part understands.
Check the parsed address, not the text
Parse an untrusted address once, with a strict parser such as ipaddress.ip_address(), reject what it cannot
read, and use the parsed value for both the check and the connection. Comparing text is not enough: 0x7f.1,
2130706433 and 127.1 all reach the loopback address through a lenient parser.
Compare the offline parser fixtures before selecting one value for an owned address policy.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- Use the six original offline strings: 127.0.0.1, 127.1, 0x7f.1, 2130706433, 0177.0.0.1 and 010.1.2.3. This figure makes no connection.
- The legacy parser reads the first five as 127.0.0.1 and the last as 8.1.2.3. The strict parser accepts the ordinary four-octet spelling and rejects the other five.
- For an owned destination policy, use the strictly parsed and actually resolved address for both the policy decision and the connection. The textual spelling alone cannot identify the used destination.
Checkpoint
Check: One strict parsed value must drive an owned address policy
A prefix writes the network boundary as contiguous bits
A prefix length /n says that the first n bits of the address are the network part and the remaining 32 − n bits are the ordinary subnet hosts: Addresses between the network and broadcast endpoints of an ordinary IPv4 subnet; point-to-point /31 and /32 contexts use different endpoint rules.. RFC 4632, the CIDR specification, writes it as the address, a slash and a number from 0 to 32. The subnet mask records the same boundary as a 32-bit value: n one-bits followed by 32 − n zero-bits, written in dotted decimal.
Where the /20 boundary falls in 10.20.30.40
Text description of the diagram
The diagram writes the address 10.20.30.40 as its 32 bits, in two rows of 16 bits with the decimal value of each octet above its 8 bits.
- Row 1 holds bits 1 to 16: 10 is 00001010 and 20 is 00010100. All 16 bits are shaded as network bits.
- Row 2 holds bits 17 to 32: 30 is 00011110 and 40 is 00101000. Only the first four bits of the third octet (0001) are shaded; a thick line after them is labelled /20.
- The legend says that the shaded cells are the network part, the first 20 bits, and the plain cells are the host part, the last 12 bits.
Because the boundary falls inside the third octet, that octet is the only one that needs binary when you work out the network and broadcast addresses: its network bits are 0001, so the network address has 16 in the third octet, and with the four host bits set to 1 the broadcast address has 31.
For /20, twenty ones fill the first two octets (255.255) and carry four bits into the third: 11110000, which is
240. The fourth octet is all zeros. So /20 and 255.255.240.0 are two spellings of one boundary. Because the ones
always come first, an octet of a mask can take only nine values: 0, 128, 192, 224, 240, 248, 252, 254 and 255.
RFC 4632 requires the mask to be contiguous, which rules out a mask such as 255.0.255.0.
Flip every bit of the mask and you get the wildcard mask: The bitwise complement of a subnet mask within the 32-bit IPv4 address width., also called the host mask: 0.0.15.255 for a /20. It marks
the host bits instead of the network bits, and some configuration languages ask for it in place of the mask.
Count the leading mask bits and locate the boundary implied by the stated prefix.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- The original /20 fixes twenty leading bits and leaves 32 − 20 = 12 host-position bits.
- Two complete octets contribute sixteen one-bits. Four more give the third octet 11110000, or 240, so the contiguous mask is 255.255.240.0.
- Flip the mask bits to get 0.0.15.255. Its twelve one-bits identify the host positions, and the original mask and wildcard remain complementary.
Checkpoint
Check: A prefix writes the network boundary as contiguous bits
Masking computes the stated block edges
Two bitwise operations give the edges of a subnet:
- network address = address AND mask, which clears every host bit to 0;
- broadcast address = network address OR wildcard mask, which sets every host bit to 1.
Take 10.20.30.40/20. The first two octets lie wholly in the network part, so they stay 10.20. The fourth octet lies
wholly in the host part, so it becomes 0 in the network address and 255 in the broadcast address. Only the third
octet, where the boundary falls, needs binary:
- the address’s third octet:
00011110, which is 30; - the mask’s third octet:
11110000, which is 240; - address AND mask:
00010000, which is 16, the third octet of the network address; - the same with the four host bits set to 1:
00011111, which is 31, the third octet of the broadcast address.
So the subnet runs from 10.20.16.0, its network address, to 10.20.31.255, its broadcast address. Hosts use everything
in between: 10.20.16.1 to 10.20.31.254. This program does the same arithmetic on the whole 32-bit number and then
asks the ipaddress module:
# Network, broadcast and host range of 10.20.30.40/20 with integer bit operations, then the same
# with the ipaddress module.
import ipaddress
def to_int(dotted):
a, b, c, d = (int(x) for x in dotted.split("."))
return (a << 24) | (b << 16) | (c << 8) | d
def to_dotted(n):
return ".".join(str((n >> shift) & 0xFF) for shift in (24, 16, 8, 0))
address, prefix = "10.20.30.40", 20
mask = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF # prefix one-bits, then zeros
wildcard = ~mask & 0xFFFFFFFF # the host bits
network = to_int(address) & mask # host bits cleared
broadcast = network | wildcard # host bits set
print("mask ", to_dotted(mask))
print("wildcard ", to_dotted(wildcard))
print("network ", to_dotted(network))
print("broadcast ", to_dotted(broadcast))
print("hosts ", to_dotted(network + 1), "to", to_dotted(broadcast - 1))
print("addresses ", 2 ** (32 - prefix), "usable", 2 ** (32 - prefix) - 2)
net = ipaddress.ip_network(f"{address}/{prefix}", strict=False)
print("ipaddress ", net, net.broadcast_address, net.num_addresses)
try:
ipaddress.ip_network(f"{address}/{prefix}")
except ValueError as error:
print("strict ", error) Output
mask 255.255.240.0 wildcard 0.0.15.255 network 10.20.16.0 broadcast 10.20.31.255 hosts 10.20.16.1 to 10.20.31.254 addresses 4096 usable 4094 ipaddress 10.20.16.0/20 10.20.31.255 4096 strict 10.20.30.40/20 has host bits set
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 network_by_hand.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Python 3.14 · main.py
import sys
def number(address: str) -> int:
value = 0
for part in address.split("."):
value = value * 256 + int(part)
return value
def dotted(value: int) -> str:
return ".".join(str((value >> shift) & 255) for shift in [24, 16, 8, 0])
for line in sys.stdin.read().splitlines():
address, bits = line.split()
prefix = int(bits)
size = 1 << (32 - prefix)
mask = 0xFFFFFFFF ^ (size - 1)
network = number(address) & mask
edge = network + size - 1
first, last = (network, edge) if prefix >= 31 else (network + 1, edge - 1)
broadcast = "none" if prefix >= 31 else dotted(edge)
print(f"{address}/{prefix} mask={dotted(mask)} network={dotted(network)}")
print(
f"last={dotted(edge)} broadcast={broadcast} first={dotted(first)} "
f"host-last={dotted(last)}"
)
print(f"addresses={size} usable={last - first + 1}") Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py < input.txt
JavaScript Node 24 · main.mjs
const fixture = "10.20.30.40 20\n192.0.2.0 29\n192.0.2.0 30\n192.0.2.0 31\n192.0.2.7 32\n";
const number = (address) =>
address.split(".").reduce((value, part) => value * 256 + Number(part), 0);
const dotted = (value) =>
[24, 16, 8, 0].map((shift) => Math.floor(value / 2 ** shift) % 256).join(".");
for (const line of fixture.trim().split(/\n/)) {
const [address, bits] = line.split(" "),
prefix = Number(bits),
size = 2 ** (32 - prefix);
const mask = (0xffffffff ^ (size - 1)) >>> 0,
network = (number(address) & mask) >>> 0,
edge = network + size - 1;
const first = prefix >= 31 ? network : network + 1,
last = prefix >= 31 ? edge : edge - 1;
const broadcast = prefix >= 31 ? "none" : dotted(edge);
console.log(`${address}/${prefix} mask=${dotted(mask)} network=${dotted(network)}`);
console.log(
`last=${dotted(edge)} broadcast=${broadcast} first=${dotted(first)} ` +
`host-last=${dotted(last)}`,
);
console.log(`addresses=${size} usable=${last - first + 1}`);
} Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs < input.txt
Java 25 LTS · Main.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
static long number(String address) {
long value = 0;
for (String p : address.split("\\.")) value = value * 256 + Integer.parseInt(p);
return value;
}
static String dotted(long value) {
var s = new StringBuilder();
for (int shift : new int[] {24, 16, 8, 0}) {
if (s.length() > 0) s.append('.');
s.append((value >> shift) & 255);
}
return s.toString();
}
public static void main(String[] args) throws Exception {
var in = new BufferedReader(new InputStreamReader(System.in));
for (String line; (line = in.readLine()) != null; ) {
if (line.isBlank()) continue;
String[] row = line.split(" ");
String address = row[0];
int prefix = Integer.parseInt(row[1]);
long size = 1L << (32 - prefix), mask = 0xffffffffL ^ (size - 1);
long network = number(address) & mask, edge = network + size - 1;
long first = prefix >= 31 ? network : network + 1, last = prefix >= 31 ? edge : edge - 1;
String broadcast = prefix >= 31 ? "none" : dotted(edge);
System.out.println(
address + "/" + prefix + " mask=" + dotted(mask) + " network=" + dotted(network));
System.out.println(
"last="
+ dotted(edge)
+ " broadcast="
+ broadcast
+ " first="
+ dotted(first)
+ " host-last="
+ dotted(last));
System.out.println("addresses=" + size + " usable=" + (last - first + 1));
}
}
} Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java < input.txt
C++23 · main.cpp
#include <cstdint>
#include <iostream>
#include <print>
#include <sstream>
#include <string>
std::uint64_t number(const std::string &address) {
std::istringstream in(address);
std::uint64_t value = 0;
for (std::string part; std::getline(in, part, '.');)
value = value * 256 + std::stoul(part);
return value;
}
std::string dotted(std::uint64_t value) {
std::string out;
for (int shift : {24, 16, 8, 0}) {
if (!out.empty())
out += ".";
out += std::to_string(value >> shift & 255);
}
return out;
}
int main() {
std::string address;
int prefix;
while (std::cin >> address >> prefix) {
const auto size = std::uint64_t{1} << (32 - prefix),
mask = std::uint64_t{0xffffffff} ^ (size - 1);
const auto network = number(address) & mask, edge = network + size - 1;
const auto first = prefix >= 31 ? network : network + 1,
last = prefix >= 31 ? edge : edge - 1;
const auto broadcast = prefix >= 31 ? "none" : dotted(edge);
std::println("{}/{} mask={} network={}", address, prefix, dotted(mask),
dotted(network));
std::println("last={} broadcast={} first={} host-last={}", dotted(edge),
broadcast, dotted(first), dotted(last));
std::println("addresses={} usable={}", size, last - first + 1);
}
} Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main < input.txt
C# 14 · .NET 10 · app.cs
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
static ulong Number(string address) =>
address.Split('.').Aggregate(0UL, (n, p) => n * 256 + ulong.Parse(p));
static string Dotted(ulong value) =>
string.Join(".", new[] { 24, 16, 8, 0 }.Select(s => (value >> s) & 255));
for (string? line; (line = Console.ReadLine()) is not null;)
{
if (line == "") continue; string[] row = line.Split(' ');
string address = row[0]; int prefix = int.Parse(row[1]);
ulong size = 1UL << (32 - prefix), mask = 0xffffffffUL ^ (size - 1);
ulong network = Number(address) & mask, edge = network + size - 1;
ulong first = prefix >= 31 ? network : network + 1, last = prefix >= 31 ? edge : edge - 1;
string broadcast = prefix >= 31 ? "none" : Dotted(edge);
Console.WriteLine($"{address}/{prefix} mask={Dotted(mask)} network={Dotted(network)}");
Console.WriteLine($"last={Dotted(edge)} broadcast={broadcast} first={Dotted(first)} "
+ $"host-last={Dotted(last)}");
Console.WriteLine($"addresses={size} usable={last - first + 1}");
} Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs < input.txt
C23 · main.c
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
static void dotted(uint64_t value, char *out) {
snprintf(out, 16, "%u.%u.%u.%u", (unsigned)(value >> 24 & 255),
(unsigned)(value >> 16 & 255), (unsigned)(value >> 8 & 255),
(unsigned)(value & 255));
}
int main(void) {
char address[16];
int prefix;
while (scanf("%15s %d", address, &prefix) == 2) {
unsigned a, b, c, d;
if (sscanf(address, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
return 1;
const uint64_t value =
(uint64_t)a << 24 | (uint64_t)b << 16 | (uint64_t)c << 8 | d;
const uint64_t size = UINT64_C(1) << (32 - prefix),
mask = UINT64_C(0xffffffff) ^ (size - 1);
const uint64_t network = value & mask, edge = network + size - 1;
const uint64_t first = prefix >= 31 ? network : network + 1,
last = prefix >= 31 ? edge : edge - 1;
char m[16], n[16], e[16], f[16], l[16];
dotted(mask, m);
dotted(network, n);
dotted(edge, e);
dotted(first, f);
dotted(last, l);
printf("%s/%d mask=%s network=%s\n", address, prefix, m, n);
printf("last=%s broadcast=%s first=%s host-last=%s\n", e,
prefix >= 31 ? "none" : e, f, l);
printf("addresses=%" PRIu64 " usable=%" PRIu64 "\n", size,
last - first + 1);
}
return 0;
} Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main < input.txt
PHP 8.5 · main.php
<?php
declare(strict_types=1);
/** @param list<int> $octets */
function dotted(array $octets): string
{
return implode('.', $octets);
}
while (($line = fgets(STDIN)) !== false) {
if (trim($line) === '') {
continue;
}
[$address, $bits] = explode(' ', trim($line));
$prefix = (int) $bits;
$octets = array_map(intval(...), explode('.', $address));
$mask = [];
$network = [];
$edge = [];
for ($i = 0; $i < 4; ++$i) {
$local = max(0, min(8, $prefix - 8 * $i));
$mask[$i] = 255 ^ ((1 << (8 - $local)) - 1);
$network[$i] = $octets[$i] & $mask[$i];
$edge[$i] = $network[$i] | (255 ^ $mask[$i]);
}
$first = $network;
$last = $edge;
if ($prefix < 31) {
++$first[3];
--$last[3];
}
$size = 1 << (32 - $prefix);
$usable = $prefix >= 31 ? $size : $size - 2;
$broadcast = $prefix >= 31 ? 'none' : dotted($edge);
echo $address . '/' . $prefix . ' mask=' . dotted($mask)
. ' network=' . dotted($network) . "\n";
echo 'last=' . dotted($edge) . ' broadcast=' . $broadcast . ' first=' . dotted($first)
. ' host-last=' . dotted($last) . "\n";
echo 'addresses=' . $size . ' usable=' . $usable . "\n";
} In PHP: The original prefix cases are masked one octet at a time so the browser runtime's 32-bit integers preserve each byte and the same block endpoints.
Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php < input.txt
Rust 1.99 · main.rs
use std::io::{self, Read};
fn dotted(value: u64) -> String {
[24, 16, 8, 0]
.iter()
.map(|&s| ((value >> s) & 255).to_string())
.collect::<Vec<_>>()
.join(".")
}
fn main() {
let mut input = String::new();
if io::stdin().read_to_string(&mut input).is_err() {
return;
}
for line in input.lines() {
let row = line.split_whitespace().collect::<Vec<_>>();
if row.is_empty() {
continue;
}
let Ok(prefix) = row[1].parse::<u32>() else {
return;
};
let Ok(parts) = row[0]
.split('.')
.map(str::parse::<u64>)
.collect::<Result<Vec<_>, _>>()
else {
return;
};
let value = parts.iter().fold(0, |v, &part| v * 256 + part);
let size = 1u64 << (32 - prefix);
let mask = 0xffffffff ^ (size - 1);
let network = value & mask;
let edge = network + size - 1;
let (first, last) = if prefix >= 31 {
(network, edge)
} else {
(network + 1, edge - 1)
};
let broadcast = if prefix >= 31 {
"none".to_string()
} else {
dotted(edge)
};
println!(
"{}/{prefix} mask={} network={}",
row[0],
dotted(mask),
dotted(network)
);
println!(
"last={} broadcast={broadcast} first={} host-last={}",
dotted(edge),
dotted(first),
dotted(last)
);
println!("addresses={size} usable={}", last - first + 1);
}
} Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main < input.txt
TypeScript 6.0 · main.ts
const fixture = "10.20.30.40 20\n192.0.2.0 29\n192.0.2.0 30\n192.0.2.0 31\n192.0.2.7 32\n";
const number = (address: string): number =>
address.split(".").reduce((value, part) => value * 256 + Number(part), 0);
const dotted = (value: number): string =>
[24, 16, 8, 0].map((shift) => Math.floor(value / 2 ** shift) % 256).join(".");
for (const line of fixture.trim().split(/\n/)) {
const [address, bits] = line.split(" "),
prefix = Number(bits),
size = 2 ** (32 - prefix);
const mask = (0xffffffff ^ (size - 1)) >>> 0,
network = (number(address) & mask) >>> 0,
edge = network + size - 1;
const first = prefix >= 31 ? network : network + 1,
last = prefix >= 31 ? edge : edge - 1;
const broadcast = prefix >= 31 ? "none" : dotted(edge);
console.log(`${address}/${prefix} mask=${dotted(mask)} network=${dotted(network)}`);
console.log(
`last=${dotted(edge)} broadcast=${broadcast} first=${dotted(first)} ` +
`host-last=${dotted(last)}`,
);
console.log(`addresses=${size} usable=${last - first + 1}`);
} Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts < input.txt
Go 1.27 · main.go
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
func number(address string) uint64 {
value := uint64(0)
for _, p := range strings.Split(address, ".") {
n, err := strconv.ParseUint(p, 10, 8)
if err != nil {
return 0
}
value = value*256 + n
}
return value
}
func dotted(value uint64) string {
parts := []string{}
for _, s := range []uint{24, 16, 8, 0} {
parts = append(parts, fmt.Sprint(value>>s&255))
}
return strings.Join(parts, ".")
}
func main() {
for {
var address string
var prefix uint
if _, err := fmt.Fscan(os.Stdin, &address, &prefix); err != nil {
return
}
size := uint64(1) << (32 - prefix)
mask := uint64(0xffffffff) ^ (size - 1)
network := number(address) & mask
edge := network + size - 1
first, last := network+1, edge-1
broadcast := dotted(edge)
if prefix >= 31 {
first, last = network, edge
broadcast = "none"
}
fmt.Printf("%s/%d mask=%s network=%s\n", address, prefix, dotted(mask), dotted(network))
fmt.Printf("last=%s broadcast=%s first=%s host-last=%s\n",
dotted(edge), broadcast, dotted(first), dotted(last))
fmt.Printf("addresses=%d usable=%d\n", size, last-first+1)
}
} Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go < input.txt
Swift 6.4 · main.swift
func number(_ address: String) -> UInt64 {
address.split(separator: ".").reduce(UInt64(0)) { value, part in value * 256 + (UInt64(part) ?? 0)
}
}
func dotted(_ value: UInt64) -> String {
[24, 16, 8, 0].map { String(value >> $0 & 255) }.joined(separator: ".")
}
while let line = readLine() {
let row = line.split(separator: " ")
if row.isEmpty { continue }
let address = String(row[0])
guard let prefix = Int(row[1]) else { break }
let size = UInt64(1) << (32 - prefix)
let mask = UInt64(0xffff_ffff) ^ (size - 1)
let network = number(address) & mask
let edge = network + size - 1
let first = prefix >= 31 ? network : network + 1
let last = prefix >= 31 ? edge : edge - 1
let broadcast = prefix >= 31 ? "none" : dotted(edge)
print("\(address)/\(prefix) mask=\(dotted(mask)) network=\(dotted(network))")
print(
"last=\(dotted(edge)) broadcast=\(broadcast) first=\(dotted(first)) "
+ "host-last=\(dotted(last))")
print("addresses=\(size) usable=\(last-first+1)")
} Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main < input.txt
Ruby 4.0 · main.rb
# frozen_string_literal: true
def dotted(value)
[24, 16, 8, 0].map { |shift| (value >> shift) & 255 }.join('.')
end
$stdin.each_line do |line|
address, bits = line.split
next unless address
prefix = bits.to_i
size = 1 << (32 - prefix)
mask = 0xffffffff ^ (size - 1)
value = address.split('.').reduce(0) { |sum, part| sum * 256 + part.to_i }
network = value & mask
edge = network + size - 1
first, last = prefix >= 31 ? [network, edge] : [network + 1, edge - 1]
broadcast = prefix >= 31 ? 'none' : dotted(edge)
puts "#{address}/#{prefix} mask=#{dotted(mask)} network=#{dotted(network)}"
puts "last=#{dotted(edge)} broadcast=#{broadcast} first=#{dotted(first)} " \
"host-last=#{dotted(last)}"
puts "addresses=#{size} usable=#{last - first + 1}"
end Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb < input.txt
Kotlin 2.4 · Main.kt
fun dotted(n: Long) = listOf(24, 16, 8, 0).joinToString(".") { ((n shr it) and 255).toString() }
fun main() {
while (true) {
val line = readlnOrNull() ?: break
if (line.isBlank()) continue
val row = line.split(" ")
val address = row[0]
val prefix = row[1].toInt()
val value = address.split(".").fold(0L) { v, p -> v * 256 + p.toLong() }
val size = 1L shl (32 - prefix)
val mask = 0xffffffffL xor (size - 1)
val network = value and mask
val edge = network + size - 1
val first = if (prefix >= 31) network else network + 1
val last = if (prefix >= 31) edge else edge - 1
val broadcast = if (prefix >= 31) "none" else dotted(edge)
println("$address/$prefix mask=${dotted(mask)} network=${dotted(network)}")
println(
"last=${dotted(edge)} broadcast=$broadcast first=${dotted(first)} " +
"host-last=${dotted(last)}",
)
println("addresses=$size usable=${last - first + 1}")
}
} Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar < input.txt
Dart 3.13 · main.dart
import 'dart:io';
String dotted(int value) =>
[24, 16, 8, 0].map((s) => (value >> s) & 255).join('.');
void main() {
for (String? line; (line = stdin.readLineSync()) != null;) {
if (line!.trim().isEmpty) continue;
final row = line.split(' ');
final address = row[0], prefix = int.parse(row[1]);
final value = address.split('.').fold(0, (v, p) => v * 256 + int.parse(p));
final size = 1 << (32 - prefix),
mask = 0xffffffff ^ (size - 1),
network = value & mask,
edge = network + size - 1;
final first = prefix >= 31 ? network : network + 1,
last = prefix >= 31 ? edge : edge - 1;
final broadcast = prefix >= 31 ? 'none' : dotted(edge);
print('$address/$prefix mask=${dotted(mask)} network=${dotted(network)}');
print(
'last=${dotted(edge)} broadcast=$broadcast first=${dotted(first)} '
'host-last=${dotted(last)}',
);
print('addresses=$size usable=${last - first + 1}');
}
} Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart < input.txt
Input (standard input)
10.20.30.40 20 192.0.2.0 29 192.0.2.0 30 192.0.2.0 31 192.0.2.7 32
What every language printed
10.20.30.40/20 mask=255.255.240.0 network=10.20.16.0 last=10.20.31.255 broadcast=10.20.31.255 first=10.20.16.1 host-last=10.20.31.254 addresses=4096 usable=4094 192.0.2.0/29 mask=255.255.255.248 network=192.0.2.0 last=192.0.2.7 broadcast=192.0.2.7 first=192.0.2.1 host-last=192.0.2.6 addresses=8 usable=6 192.0.2.0/30 mask=255.255.255.252 network=192.0.2.0 last=192.0.2.3 broadcast=192.0.2.3 first=192.0.2.1 host-last=192.0.2.2 addresses=4 usable=2 192.0.2.0/31 mask=255.255.255.254 network=192.0.2.0 last=192.0.2.1 broadcast=none first=192.0.2.0 host-last=192.0.2.1 addresses=2 usable=2 192.0.2.7/32 mask=255.255.255.255 network=192.0.2.7 last=192.0.2.7 broadcast=none first=192.0.2.7 host-last=192.0.2.7 addresses=1 usable=1
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 58 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 159 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 3 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 18 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads PHP (about 4.3 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 23 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 771 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 188 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 16 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
The last line shows a common trap. ip_network("10.20.30.40/20") raises ValueError because the address has host
bits set: an address with host bits is a host, not a network. Pass strict=False when you mean “the network this
address is in”, or use ipaddress.ip_interface(), which keeps the address and its network together.
The two edge addresses have jobs of their own. The network address names the subnet itself, for example in a routing table. The broadcast address reaches every host on the subnet at once, and RFC 1122 forbids it as the source of a packet. A packet sent to the broadcast address of a distant subnet is a directed broadcast, and routers no longer pass those on by default: RFC 2644 changed the default because almost all directed broadcasts crossing the Internet were attacks that used a whole subnet to multiply traffic towards a victim.
Subnet Calculator Type any address with a prefix or mask to see its network, broadcast address, host range and binary form, and check the answers you work out by hand.Apply the /20 mask to the worked address and check both block endpoints.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- Keep 10.20.30.40 and its original /20 mask. The boundary falls in the third octet, while the fourth octet is entirely in the host part.
- AND clears the host positions: 00011110 AND 11110000 is 00010000, or 16. The network is 10.20.16.0.
- OR with 0.0.15.255 reaches 10.20.31.255. The ordinary host range is 10.20.16.1 through 10.20.31.254: 4096 − 2 = 4094 hosts.
Checkpoint
Check: Masking computes the stated block edges
The usable endpoint rule depends on prefix and link context
A prefix of length n leaves h = 32 − n host bits, so its block holds 2^h addresses. An ordinary subnet gives two of them to the network and broadcast addresses, which leaves 2^h − 2 for hosts: 254 in a /24, 30 in a /27 and 2 in a /30.
Two prefix lengths break the rule:
- /32 is a single address. It names one host, for example a route to one server or the loopback address of a router; the table in RFC 4632 calls a /32 a host route.
- /31 has two addresses, no room for both a network and a broadcast address. RFC 3021 lets point-to-point links use it: on such a link both addresses are host addresses. A link then uses two addresses instead of the four of a /30, which halves the addresses spent on links between routers.
# The smallest prefixes: usable addresses, and what Python's ipaddress module reports for each.
import ipaddress
print(f"{'prefix':<14}{'size':>4}{'usable':>8} broadcast_address")
for text in ["192.0.2.0/29", "192.0.2.0/30", "192.0.2.0/31", "192.0.2.7/32"]:
net = ipaddress.ip_network(text)
print(f"{text:<14}{net.num_addresses:>4}{len(list(net.hosts())):>8} {net.broadcast_address}")
print("hosts() of the /31:", ", ".join(str(h) for h in ipaddress.ip_network("192.0.2.0/31").hosts())) Output
prefix size usable broadcast_address 192.0.2.0/29 8 6 192.0.2.7 192.0.2.0/30 4 2 192.0.2.3 192.0.2.0/31 2 2 192.0.2.1 192.0.2.7/32 1 1 192.0.2.7 hosts() of the /31: 192.0.2.0, 192.0.2.1
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 small_prefixes.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Python follows RFC 3021 in hosts(), which returns both addresses of a /31. Its broadcast_address attribute still
reports the last address of the block for a /31 and a /32, though, so code that removes broadcast_address from a
/31 throws away a working address. Check the prefix length before you treat the last address as a broadcast address.
In exam questions, count 2^h − 2 hosts unless the question is about a /31 point-to-point link.
Inspect the /29, /30, /31 and /32 cases before counting usable endpoints.
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- 192.0.2.0/29 spans .0 through .7. An ordinary subnet reserves its two edges, leaving .1 through .6 as six hosts.
- 192.0.2.0/30 spans .0 through .3. Its ordinary hosts are .1 and .2, giving two endpoints.
- 192.0.2.0/31 spans .0 and .1. On the stated RFC 3021 point-to-point link both are host endpoints; the library's last-address attribute does not remove either.
- 192.0.2.7/32 names only .7, one host route. This single-address case uses neither the ordinary LAN subtraction nor a broadcast endpoint.
Checkpoint
Check: The usable endpoint rule depends on prefix and link context
CIDR carries an explicit prefix instead of inferring a class
The first IPv4 specification fixed the size of the network part by the first bits of the address. RFC 791 defined classes A, B and C, and RFC 1112 later used the next range for multicast:
- Class A: first bit
0, first octet 0 to 127, an 8-bit network part (/8); unicast. - Class B: first bits
10, first octet 128 to 191, a 16-bit network part (/16); unicast. - Class C: first bits
110, first octet 192 to 223, a 24-bit network part (/24); unicast. - Class D: first bits
1110, first octet 224 to 239; multicast groups, with no network part. - Class E: first bits
1111, first octet 240 to 255; reserved.
An organisation received a whole class A, B or C network and nothing in between. RFC 4632 describes what went wrong. A class C network (254 hosts) was too small for most organisations and a class B network (65,534 hosts) far too large, so class B numbers were running out by the early 1990s. At the same time the routing tables of the Internet’s core routers were growing faster than the hardware and software could keep up with. Classless Inter-Domain Routing dropped the classes. A block can be any power-of-two size, its prefix length is written down explicitly, and routing protocols carry the prefix length with every route. Neighbouring blocks can then be announced as one shorter prefix, which keeps routing tables small; a later lesson of this module, on VLSM and route summarisation, does exactly that.
CIDR slowed the use of addresses, but it could not make more of them. IANA’s free pool of IPv4 addresses ran out in 2011, when its last five /8 blocks went one to each of the five regional Internet registries. Sharing one address among many devices with NAT, and moving to IPv6, are the two answers, and both have their own lessons in this track.
Classes still appear in exam questions, in old documentation and in tool output, so it pays to recognise them by their first bits. They decide nothing in a modern network: 10.20.30.40 is a class A address, but its prefix in this lesson is /20.
GATE CS
The GATE 2027 syllabus for Computer Science lists “IPv4 - Fragmentation, CIDR Notation, Network Address Translation” in its computer networks section. This module covers CIDR notation and network address translation; fragmentation has its own lesson in the next module.
Contrast an explicit CIDR prefix with the historical class inferred from a first octet.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- The original 10.20.30.40 address has the historical class A first-bit pattern. That historical scheme inferred an eight-bit network part.
- Read the supplied /20 instead: twenty bits are fixed and twelve vary. The configured block has 4096 addresses, regardless of the historical class label.
- CIDR carries explicit prefix lengths with routes and allows aligned power-of-two blocks to be aggregated. The later VLSM example works from those explicit boundaries.
Checkpoint
Check: CIDR carries an explicit prefix instead of inferring a class
A listed special prefix has a specific scope and purpose
Some blocks are set aside by standards and are never used as ordinary public addresses. IANA keeps them in the IPv4 Special-Purpose Address Registry, whose rules are set out in RFC 6890. For each block, the registry records whether it may appear as a source or a destination, whether routers may forward it and whether it is globally reachable. None of these blocks is globally reachable:
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16: private use inside one organisation (RFC 1918).- 100.64.0.0/10: shared space between a customer’s router and an ISP’s carrier-grade NAT (RFC 6598).
- 127.0.0.0/8: loopback, the host itself; these addresses must never appear outside the host (RFC 1122).
- 169.254.0.0/16: link-local, the addresses a host gives itself when nothing else configures one; routers do not forward them (RFC 3927).
- 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24: documentation and examples (RFC 5737).
- 198.18.0.0/15: benchmarking network equipment (RFC 2544).
- 0.0.0.0/8: “this network”; the single address 0.0.0.0 is the source of a host that has no address yet (RFC 791, RFC 1122).
- 240.0.0.0/4: reserved (RFC 1112).
- 255.255.255.255/32: the limited broadcast address, every host on the local network (RFC 919, RFC 8190).
The multicast range 224.0.0.0/4, class D above, is not a special-purpose block: its addresses name groups of receivers rather than single hosts (RFC 1112). Anyone may use the private-use blocks without asking a registry, so countless home and office networks use the same addresses at the same time; these addresses are not globally unique or intended for public Internet routing. A private host can use a translating gateway or an application gateway to reach public services.
# Which special-purpose block an address is in, from a table of the IANA IPv4 Special-Purpose
# Address Registry (RFC 6890) and the multicast range of RFC 1112. When two blocks contain an
# address, the longer prefix (the more specific block) wins.
import ipaddress
SPECIAL = [
("0.0.0.0/8", "this network"),
("10.0.0.0/8", "private-use (RFC 1918)"),
("100.64.0.0/10", "shared CGN space (RFC 6598)"),
("127.0.0.0/8", "loopback"),
("169.254.0.0/16", "link-local (RFC 3927)"),
("172.16.0.0/12", "private-use (RFC 1918)"),
("192.0.2.0/24", "documentation (RFC 5737)"),
("192.168.0.0/16", "private-use (RFC 1918)"),
("198.18.0.0/15", "benchmarking (RFC 2544)"),
("198.51.100.0/24", "documentation (RFC 5737)"),
("203.0.113.0/24", "documentation (RFC 5737)"),
("224.0.0.0/4", "multicast (RFC 1112)"),
("240.0.0.0/4", "reserved (RFC 1112)"),
("255.255.255.255/32", "limited broadcast"),
]
TABLE = [(ipaddress.ip_network(block), name) for block, name in SPECIAL]
def kind(text):
address = ipaddress.ip_address(text)
matches = [(net.prefixlen, name) for net, name in TABLE if address in net]
return max(matches)[1] if matches else "public unicast"
for text in ["10.1.2.3", "172.31.255.254", "172.32.0.1", "192.168.1.1", "100.72.160.1", "100.128.0.1",
"127.0.0.53", "169.254.10.20", "198.51.100.7", "224.0.0.251", "255.255.255.255", "0.0.0.0"]:
print(f"{text:<16} {kind(text)}") Output
10.1.2.3 private-use (RFC 1918) 172.31.255.254 private-use (RFC 1918) 172.32.0.1 public unicast 192.168.1.1 private-use (RFC 1918) 100.72.160.1 shared CGN space (RFC 6598) 100.128.0.1 public unicast 127.0.0.53 loopback 169.254.10.20 link-local (RFC 3927) 198.51.100.7 documentation (RFC 5737) 224.0.0.251 multicast (RFC 1112) 255.255.255.255 limited broadcast 0.0.0.0 this network
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 special_ranges.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Python 3.14 · main.py
import sys
def number(address: str) -> int:
return sum(int(part) << (8 * (3 - i)) for i, part in enumerate(address.split(".")))
rows = iter(sys.stdin.read().splitlines())
table = []
for _ in range(int(next(rows))):
address, bits, label = next(rows).split()
prefix = int(bits)
table.append((number(address), prefix, label))
for address in rows:
value = number(address)
best = -1
label = "not-in-listed-ranges"
for base, prefix, name in table:
mask = 0xFFFFFFFF ^ ((1 << (32 - prefix)) - 1)
if value & mask == base and prefix > best:
best, label = prefix, name
print(f"{address} {label}") Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py < input.txt
JavaScript Node 24 · main.mjs
const fixture =
"14\n0.0.0.0 8 this-network\n10.0.0.0 8 rfc1918\n100.64.0.0 10 shared\n" +
"127.0.0.0 8 loopback\n169.254.0.0 16 link-local\n172.16.0.0 12 rfc1918\n" +
"192.0.2.0 24 documentation\n192.168.0.0 16 rfc1918\n198.18.0.0 15 benchmark\n" +
"198.51.100.0 24 documentation\n203.0.113.0 24 documentation\n" +
"224.0.0.0 4 multicast\n240.0.0.0 4 reserved\n" +
"255.255.255.255 32 limited-broadcast\n10.1.2.3\n172.31.255.254\n172.32.0.1\n" +
"192.168.1.1\n100.72.160.1\n100.128.0.1\n127.0.0.53\n169.254.10.20\n198.51.100.7\n" +
"224.0.0.251\n255.255.255.255\n0.0.0.0\n";
const number = (address) => address.split(".").reduce((v, p) => v * 256 + Number(p), 0);
const rows = fixture.trim().split(/\n/),
count = Number(rows[0]);
const table = rows.slice(1, count + 1).map((line) => {
const [address, bits, label] = line.split(" ");
return [number(address), Number(bits), label];
});
for (const address of rows.slice(count + 1)) {
const value = number(address);
let best = -1,
label = "not-in-listed-ranges";
for (const [base, prefix, name] of table) {
const mask = (0xffffffff ^ (2 ** (32 - prefix) - 1)) >>> 0;
if ((value & mask) >>> 0 === base && prefix > best) {
best = prefix;
label = name;
}
}
console.log(`${address} ${label}`);
} Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs < input.txt
Java 25 LTS · Main.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
record Range(long base, int prefix, String label) {}
static long number(String address) {
long value = 0;
for (String p : address.split("\\.")) value = value * 256 + Integer.parseInt(p);
return value;
}
public static void main(String[] args) throws Exception {
var reader = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(reader.readLine());
Range[] table = new Range[count];
for (int i = 0; i < count; i++) {
String[] r = reader.readLine().split(" ");
table[i] = new Range(number(r[0]), Integer.parseInt(r[1]), r[2]);
}
for (String address; (address = reader.readLine()) != null; ) {
if (address.isBlank()) continue;
long value = number(address);
int best = -1;
String label = "not-in-listed-ranges";
for (Range r : table) {
long mask = 0xffffffffL ^ ((1L << (32 - r.prefix())) - 1);
if ((value & mask) == r.base() && r.prefix() > best) {
best = r.prefix();
label = r.label();
}
}
System.out.println(address + " " + label);
}
}
} Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java < input.txt
C++23 · main.cpp
#include <cstdint>
#include <iostream>
#include <print>
#include <sstream>
#include <string>
#include <vector>
struct Row {
std::uint64_t base;
int prefix;
std::string label;
};
std::uint64_t number(const std::string &address) {
std::istringstream in(address);
std::uint64_t value = 0;
for (std::string p; std::getline(in, p, '.');)
value = value * 256 + std::stoul(p);
return value;
}
int main() {
int count;
std::cin >> count;
std::vector<Row> table;
for (int i = 0; i < count; i++) {
std::string address, label;
int prefix;
std::cin >> address >> prefix >> label;
table.push_back({number(address), prefix, label});
}
for (std::string address; std::cin >> address;) {
const auto value = number(address);
int best = -1;
std::string label = "not-in-listed-ranges";
for (const auto &r : table) {
const auto mask = std::uint64_t{0xffffffff} ^
((std::uint64_t{1} << (32 - r.prefix)) - 1);
if ((value & mask) == r.base && r.prefix > best) {
best = r.prefix;
label = r.label;
}
}
std::println("{} {}", address, label);
}
} Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main < input.txt
C# 14 · .NET 10 · app.cs
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
static ulong Number(string address) =>
address.Split('.').Aggregate(0UL, (v, p) => v * 256 + ulong.Parse(p));
int count = int.Parse(Console.ReadLine() ?? throw new InvalidOperationException());
(ulong Base, int Prefix, string Label)[] table = new (ulong, int, string)[count];
for (int i = 0; i < count; i++)
{
string[] r = (Console.ReadLine() ?? throw new InvalidOperationException()).Split(' ');
table[i] = (Number(r[0]), int.Parse(r[1]), r[2]);
}
for (string? address; (address = Console.ReadLine()) is not null;)
{
if (address == "") continue; ulong value = Number(address); int best = -1;
string label = "not-in-listed-ranges";
foreach (var r in table)
{
ulong mask = 0xffffffffUL ^ ((1UL << (32 - r.Prefix)) - 1);
if ((value & mask) == r.Base && r.Prefix > best) { best = r.Prefix; label = r.Label; }
}
Console.WriteLine(address + " " + label);
} Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs < input.txt
C23 · main.c
#include <stdint.h>
#include <stdio.h>
#include <string.h>
typedef struct {
uint64_t base;
int prefix;
char label[32];
} Row;
static uint64_t number(const char *address) {
unsigned a, b, c, d;
if (sscanf(address, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
return 0;
return (uint64_t)a << 24 | (uint64_t)b << 16 | (uint64_t)c << 8 | d;
}
int main(void) {
int count;
if (scanf("%d", &count) != 1 || count < 0 || count > 20)
return 1;
Row table[20];
for (int i = 0; i < count; i++) {
char address[16];
if (scanf("%15s %d %31s", address, &table[i].prefix, table[i].label) != 3)
return 1;
table[i].base = number(address);
}
char address[16];
while (scanf("%15s", address) == 1) {
const uint64_t value = number(address);
int best = -1;
const char *label = "not-in-listed-ranges";
for (int i = 0; i < count; i++) {
const uint64_t mask =
UINT64_C(0xffffffff) ^ ((UINT64_C(1) << (32 - table[i].prefix)) - 1);
if ((value & mask) == table[i].base && table[i].prefix > best) {
best = table[i].prefix;
label = table[i].label;
}
}
printf("%s %s\n", address, label);
}
return 0;
} Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main < input.txt
PHP 8.5 · main.php
<?php
declare(strict_types=1);
/** @return list<int> */
function octets(string $address): array
{
return array_map(intval(...), explode('.', $address));
}
/** @param list<int> $address @param list<int> $base */
function contains(array $address, array $base, int $prefix): bool
{
for ($i = 0; $i < 4; ++$i) {
$bits = max(0, min(8, $prefix - 8 * $i));
$mask = 255 ^ ((1 << (8 - $bits)) - 1);
if (($address[$i] & $mask) !== $base[$i]) {
return false;
}
}
return true;
}
$count = (int) fgets(STDIN);
$table = [];
for ($i = 0; $i < $count; ++$i) {
[$address,$prefix,$label] = explode(' ', trim((string) fgets(STDIN)));
$table[] = [octets($address),(int) $prefix,$label];
}
while (($line = fgets(STDIN)) !== false) {
$address = trim($line);
if ($address === '') {
continue;
}
$value = octets($address);
$best = -1;
$label = 'not-in-listed-ranges';
foreach ($table as [$base,$prefix,$name]) {
if (contains($value, $base, $prefix) && $prefix > $best) {
$best = $prefix;
$label = $name;
}
}
echo $address . ' ' . $label . "\n";
} In PHP: Each prefix is masked one byte at a time, preserving the original 32-bit address bits on the browser runtime's 32-bit integer path.
Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php < input.txt
Rust 1.99 · main.rs
use std::io::{self, Read};
fn number(address: &str) -> Option<u64> {
let mut value = 0;
for part in address.split('.') {
let n = part.parse::<u64>().ok()?;
value = value * 256 + n;
}
Some(value)
}
fn main() {
let mut input = String::new();
if io::stdin().read_to_string(&mut input).is_err() {
return;
}
let mut rows = input.lines();
let Some(first) = rows.next() else { return };
let Ok(count) = first.parse::<usize>() else {
return;
};
let mut table = Vec::new();
for _ in 0..count {
let Some(line) = rows.next() else { return };
let r = line.split_whitespace().collect::<Vec<_>>();
let (Some(base), Ok(prefix)) = (number(r[0]), r[1].parse::<u32>()) else {
return;
};
table.push((base, prefix, r[2]));
}
for address in rows {
let Some(value) = number(address) else { return };
let mut best = -1;
let mut label = "not-in-listed-ranges";
for &(base, prefix, name) in &table {
let mask = 0xffffffffu64 ^ ((1u64 << (32 - prefix)) - 1);
if value & mask == base && prefix as i32 > best {
best = prefix as i32;
label = name;
}
}
println!("{address} {label}");
}
} Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main < input.txt
TypeScript 6.0 · main.ts
const fixture =
"14\n0.0.0.0 8 this-network\n10.0.0.0 8 rfc1918\n100.64.0.0 10 shared\n" +
"127.0.0.0 8 loopback\n169.254.0.0 16 link-local\n172.16.0.0 12 rfc1918\n" +
"192.0.2.0 24 documentation\n192.168.0.0 16 rfc1918\n198.18.0.0 15 benchmark\n" +
"198.51.100.0 24 documentation\n203.0.113.0 24 documentation\n" +
"224.0.0.0 4 multicast\n240.0.0.0 4 reserved\n" +
"255.255.255.255 32 limited-broadcast\n10.1.2.3\n172.31.255.254\n172.32.0.1\n" +
"192.168.1.1\n100.72.160.1\n100.128.0.1\n127.0.0.53\n169.254.10.20\n198.51.100.7\n" +
"224.0.0.251\n255.255.255.255\n0.0.0.0\n";
const number = (address: string): number =>
address.split(".").reduce((v, p) => v * 256 + Number(p), 0);
const rows = fixture.trim().split(/\n/),
count = Number(rows[0]);
const table: [number, number, string][] = rows.slice(1, count + 1).map((line) => {
const [address, bits, label] = line.split(" ");
return [number(address), Number(bits), label];
});
for (const address of rows.slice(count + 1)) {
const value = number(address);
let best = -1,
label = "not-in-listed-ranges";
for (const [base, prefix, name] of table) {
const mask = (0xffffffff ^ (2 ** (32 - prefix) - 1)) >>> 0;
if ((value & mask) >>> 0 === base && prefix > best) {
best = prefix;
label = name;
}
}
console.log(`${address} ${label}`);
} Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts < input.txt
Go 1.27 · main.go
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
type row struct {
base uint64
prefix uint
label string
}
func number(address string) uint64 {
value := uint64(0)
for _, p := range strings.Split(address, ".") {
n, err := strconv.ParseUint(p, 10, 8)
if err != nil {
return 0
}
value = value*256 + n
}
return value
}
func main() {
var count int
fmt.Fscan(os.Stdin, &count)
table := make([]row, count)
for i := range table {
var address string
fmt.Fscan(os.Stdin, &address, &table[i].prefix, &table[i].label)
table[i].base = number(address)
}
for {
var address string
if _, err := fmt.Fscan(os.Stdin, &address); err != nil {
return
}
value := number(address)
best := -1
label := "not-in-listed-ranges"
for _, r := range table {
mask := uint64(0xffffffff) ^ ((uint64(1) << (32 - r.prefix)) - 1)
if value&mask == r.base && int(r.prefix) > best {
best = int(r.prefix)
label = r.label
}
}
fmt.Println(address, label)
}
} Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go < input.txt
Swift 6.4 · main.swift
func number(_ address: String) -> UInt64 {
address.split(separator: ".").reduce(UInt64(0)) { $0 * 256 + (UInt64($1) ?? 0) }
}
guard let first = readLine(), let count = Int(first) else { fatalError("missing table") }
var table = [(UInt64, Int, String)]()
for _ in 0..<count {
guard let line = readLine() else { break }
let row = line.split(separator: " ")
guard let prefix = Int(row[1]) else { break }
table.append((number(String(row[0])), prefix, String(row[2])))
}
while let address = readLine() {
let value = number(address)
var best = -1
var label = "not-in-listed-ranges"
for (base, prefix, name) in table {
let mask = UInt64(0xffff_ffff) ^ ((UInt64(1) << (32 - prefix)) - 1)
if value & mask == base && prefix > best {
best = prefix
label = name
}
}
print("\(address) \(label)")
} Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main < input.txt
Ruby 4.0 · main.rb
# frozen_string_literal: true
def number(address)
address.split('.').reduce(0) { |value, part| value * 256 + part.to_i }
end
count = $stdin.gets.to_i
table = Array.new(count) do
address, prefix, label = $stdin.gets.split
[number(address), prefix.to_i, label]
end
$stdin.each_line do |line|
address = line.strip
value = number(address)
best = -1
label = 'not-in-listed-ranges'
table.each do |base, prefix, name|
mask = 0xffffffff ^ ((1 << (32 - prefix)) - 1)
next unless value & mask == base && prefix > best
best = prefix
label = name
end
puts "#{address} #{label}"
end Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb < input.txt
Kotlin 2.4 · Main.kt
data class Range(
val base: Long,
val prefix: Int,
val label: String,
)
fun number(address: String) = address.split(".").fold(0L) { v, p -> v * 256 + p.toLong() }
fun main() {
val count = readln().toInt()
val table =
List(count) {
val r = readln().split(" ")
Range(number(r[0]), r[1].toInt(), r[2])
}
while (true) {
val address = readlnOrNull() ?: break
if (address.isBlank()) continue
val value = number(address)
var best = -1
var label = "not-in-listed-ranges"
for (r in table) {
val mask = 0xffffffffL xor ((1L shl (32 - r.prefix)) - 1)
if ((value and mask) == r.base && r.prefix > best) {
best = r.prefix
label = r.label
}
}
println("$address $label")
}
} Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar < input.txt
Dart 3.13 · main.dart
import 'dart:io';
int number(String address) =>
address.split('.').fold(0, (v, p) => v * 256 + int.parse(p));
void main() {
final count = int.parse(stdin.readLineSync() ?? '0');
final table = <(int, int, String)>[];
for (var i = 0; i < count; i++) {
final r = (stdin.readLineSync() ?? '').split(' ');
table.add((number(r[0]), int.parse(r[1]), r[2]));
}
for (String? address; (address = stdin.readLineSync()) != null;) {
if (address!.isEmpty) continue;
final value = number(address);
var best = -1, label = 'not-in-listed-ranges';
for (final (base, prefix, name) in table) {
final mask = 0xffffffff ^ ((1 << (32 - prefix)) - 1);
if ((value & mask) == base && prefix > best) {
best = prefix;
label = name;
}
}
print('$address $label');
}
} Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart < input.txt
Input (standard input)
14 0.0.0.0 8 this-network 10.0.0.0 8 rfc1918 100.64.0.0 10 shared 127.0.0.0 8 loopback 169.254.0.0 16 link-local 172.16.0.0 12 rfc1918 192.0.2.0 24 documentation 192.168.0.0 16 rfc1918 198.18.0.0 15 benchmark 198.51.100.0 24 documentation 203.0.113.0 24 documentation 224.0.0.0 4 multicast 240.0.0.0 4 reserved 255.255.255.255 32 limited-broadcast 10.1.2.3 172.31.255.254 172.32.0.1 192.168.1.1 100.72.160.1 100.128.0.1 127.0.0.53 169.254.10.20 198.51.100.7 224.0.0.251 255.255.255.255 0.0.0.0
What every language printed
10.1.2.3 rfc1918 172.31.255.254 rfc1918 172.32.0.1 not-in-listed-ranges 192.168.1.1 rfc1918 100.72.160.1 shared 100.128.0.1 not-in-listed-ranges 127.0.0.53 loopback 169.254.10.20 link-local 198.51.100.7 documentation 224.0.0.251 multicast 255.255.255.255 limited-broadcast 0.0.0.0 this-network
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 57 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 159 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 3 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 18 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads PHP (about 4.3 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 23 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 763 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 187 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 16 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
Watch the edges. 172.31.255.254 is private but 172.32.0.1 is not, because 172.16.0.0/12 ends at 172.31.255.255. In the same way 100.127.255.255 is the last shared address, so 100.128.0.1 is ordinary public space. The program picks the longest matching prefix, so it reports 255.255.255.255 as the limited broadcast address although that address also lies inside the reserved block 240.0.0.0/4. Routers choose between overlapping routes the same way.
Match each sample address to its most specific listed range and stated purpose.
The drawing shows the whole scene; its 12 steps are listed below.
Every step as text
- Input 10.1.2.3 selects 10.0.0.0/8: RFC 1918 private use. The original model chooses the most specific listed match.
- Input 172.31.255.254 selects 172.16.0.0/12: RFC 1918 private use. The original model chooses the most specific listed match.
- Input 172.32.0.1 selects No listed match: Model: public unicast. No listed match is only this table's classification, not proof of reachability.
- Input 192.168.1.1 selects 192.168.0.0/16: RFC 1918 private use. The original model chooses the most specific listed match.
- Input 100.72.160.1 selects 100.64.0.0/10: Shared CGN space. The original model chooses the most specific listed match.
- Input 100.128.0.1 selects No listed match: Model: public unicast. No listed match is only this table's classification, not proof of reachability.
- Input 127.0.0.53 selects 127.0.0.0/8: Loopback. The original model chooses the most specific listed match.
- Input 169.254.10.20 selects 169.254.0.0/16: Link-local. The original model chooses the most specific listed match.
- Input 198.51.100.7 selects 198.51.100.0/24: Documentation. The original model chooses the most specific listed match.
- Input 224.0.0.251 selects 224.0.0.0/4: Multicast. The original model chooses the most specific listed match.
- Input 255.255.255.255 selects 255.255.255.255/32: Limited broadcast. The /32 wins over the also-matching reserved /4.
- Input 0.0.0.0 selects 0.0.0.0/8: This network. The original model chooses the most specific listed match.
Checkpoint
Check: A listed special prefix has a specific scope and purpose
Library private flags differ from the three RFC1918 blocks
The ipaddress module has flags for these blocks, but their names can mislead. Its documentation defines
is_private as “not globally reachable” in the IANA registries, which includes the documentation blocks, and the
shared block 100.64.0.0/10 is neither private nor global:
# is_private in Python's ipaddress module means "not globally reachable" in the IANA registry,
# which is wider than the three private-use blocks of RFC 1918.
import ipaddress
RFC1918 = [ipaddress.ip_network(n) for n in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")]
print(f"{'address':<14} {'is_private':<11} {'is_global':<10} in RFC 1918")
for text in ["192.168.1.1", "198.51.100.7", "100.72.160.1", "100.128.0.1"]:
a = ipaddress.ip_address(text)
print(f"{text:<14} {a.is_private!s:<11} {a.is_global!s:<10} {any(a in n for n in RFC1918)}") Output
address is_private is_global in RFC 1918 192.168.1.1 True False True 198.51.100.7 True False False 100.72.160.1 False False False 100.128.0.1 False True False
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 python_flags.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
To test for the three RFC 1918 blocks, compare with the blocks themselves, as the last column does.
Documentation addresses in examples
RFC 5737 sets aside three blocks for documentation: 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24. Examples, slides and test data can use these reserved blocks without naming an assigned public host. The reservation is not runtime isolation: a locally configured endpoint can still use one, so keep example traffic off the public Internet.
Separate membership in the RFC1918 blocks from the original library classification flags.
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- 192.168.1.1 is in the private /16. The retained Python run prints is_private=True, is_global=False and RFC1918 membership=True.
- 198.51.100.7 is a documentation address. The retained run prints is_private=True and is_global=False, but it is outside the three RFC1918 blocks.
- 100.72.160.1 is in shared 100.64.0.0/10. Both library flags are False in the retained run, and RFC1918 membership is also False.
- 100.128.0.1 lies beyond the shared /10. The retained run prints is_private=False, is_global=True and RFC1918 membership=False.
Checkpoint
Check: Library private flags differ from the three RFC1918 blocks
Practise the stated IPv4 address and packet contracts
Exercise · Easy · Python
Describe the subnet an address belongs to
Write subnet_info(address, prefix), which describes the subnet that an IPv4 address belongs to. address is a dotted-decimal string such as "10.20.30.40" and prefix is the prefix length, a whole number from 0 to 32.
Return a dictionary with these five keys:
"network": the network address, as a dotted-decimal string (the host bits all 0)."broadcast": the broadcast address (the host bits all 1), orNonefor a /31 or a /32, which have no broadcast address."first"and"last": the first and last usable host addresses."usable": how many usable host addresses the subnet has, as an int.
Follow the rules of the lesson: an ordinary subnet loses its network and broadcast addresses, a /31 point-to-point link uses both of its addresses (RFC 3021), and a /32 is one host. For subnet_info("10.20.30.40", 20) the answer is {"network": "10.20.16.0", "broadcast": "10.20.31.255", "first": "10.20.16.1", "last": "10.20.31.254", "usable": 4094}.
You may do the bit arithmetic yourself or use the ipaddress module, but watch what it reports for a /31. The sample tests import your function from subnet_info.py.
Starter code · subnet_info.py
def subnet_info(address, prefix):
"""Describe the subnet of address/prefix: network, broadcast, first, last and usable."""
# Replace this line with your code.
return {} The sample tests · test_subnet_info.py
from subnet_info import subnet_info
def test_inside_a_slash_20():
"""finds the subnet of an address inside a /20"""
assert subnet_info("10.20.30.40", 20) == {
"network": "10.20.16.0", "broadcast": "10.20.31.255",
"first": "10.20.16.1", "last": "10.20.31.254", "usable": 4094,
}
def test_slash_24():
"""works when the boundary falls between octets"""
assert subnet_info("192.168.1.77", 24) == {
"network": "192.168.1.0", "broadcast": "192.168.1.255",
"first": "192.168.1.1", "last": "192.168.1.254", "usable": 254,
}
def test_network_and_broadcast_given():
"""accepts the network or the broadcast address itself"""
expected = {
"network": "192.168.10.64", "broadcast": "192.168.10.95",
"first": "192.168.10.65", "last": "192.168.10.94", "usable": 30,
}
assert subnet_info("192.168.10.64", 27) == expected
assert subnet_info("192.168.10.95", 27) == expected
def test_slash_30():
"""leaves two usable hosts in a /30"""
assert subnet_info("10.0.0.5", 30) == {
"network": "10.0.0.4", "broadcast": "10.0.0.7",
"first": "10.0.0.5", "last": "10.0.0.6", "usable": 2,
}
def test_slash_31():
"""follows RFC 3021 on a /31: no broadcast address, both addresses usable"""
assert subnet_info("192.0.2.1", 31) == {
"network": "192.0.2.0", "broadcast": None,
"first": "192.0.2.0", "last": "192.0.2.1", "usable": 2,
}
def test_slash_32():
"""treats a /32 as a single host"""
assert subnet_info("198.51.100.9", 32) == {
"network": "198.51.100.9", "broadcast": None,
"first": "198.51.100.9", "last": "198.51.100.9", "usable": 1,
}
def test_short_prefixes():
"""works for /8 and for the whole address space"""
assert subnet_info("10.200.1.2", 8) == {
"network": "10.0.0.0", "broadcast": "10.255.255.255",
"first": "10.0.0.1", "last": "10.255.255.254", "usable": 16777214,
}
assert subnet_info("203.0.113.9", 0)["usable"] == 4294967294
assert subnet_info("203.0.113.9", 0)["broadcast"] == "255.255.255.255"
def test_boundary_inside_the_second_octet():
"""handles a boundary inside the second octet"""
assert subnet_info("172.20.130.5", 14) == {
"network": "172.20.0.0", "broadcast": "172.23.255.255",
"first": "172.20.0.1", "last": "172.23.255.254", "usable": 262142,
} A hint
Turn the address into one 32-bit integer first (int(ipaddress.ip_address(address)), or shift the four octets together). The mask is prefix one-bits followed by zeros: (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF. Then the network is value & mask and the last address of the block is network | (~mask & 0xFFFFFFFF). Handle prefix 31 and 32 before the general case.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Practice that adapts to you
Practise this lesson
14 questions about 8 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
A colleague says the router-to-router link 10.0.0.0/31 cannot work, because a /31 has no usable hosts. Who is right, and where do /30, /31 and /32 each belong in a network design?
-
Mid to senior
An internal service fetches URLs for users and refuses any URL whose host text starts with "127.". A request for http://0x7f.1/admin still reaches a local admin page. Explain why, and how you would fix the check.
What is the difference between a subnet mask and a prefix length?
They carry the same information in two notations. A prefix length /n says that the first n bits of the address are the network part. A subnet mask writes that boundary as a 32-bit number with n one-bits followed by zeros, in dotted decimal: /20 is 255.255.240.0, because twenty ones fill two octets (255.255) and four more make 11110000, which is 240. To go back, count the one-bits: 8 + 8 + 4 = 20. The ones must be contiguous, so 255.0.255.0 is not a valid mask. Which form you type depends on the software; CIDR notation uses the prefix length because it is shorter.
Key takeaways
- An IPv4 address is a 32-bit number; dotted decimal, binary, hexadecimal and the integer are four ways to write it. /n puts the first n bits in the network part, and the mask is n one-bits: /20 is 255.255.240.0.
- Network address = address AND mask; broadcast address = network address OR wildcard mask; hosts use the addresses in between.
- A /n block has 2^(32 − n) addresses and 2^(32 − n) − 2 usable hosts, except a /31 link (2 hosts, RFC 3021) and a /32 (1 host).
- Address classes are history: CIDR writes the prefix length explicitly so that blocks of any power-of-two size can be assigned and aggregated.
- Know the special blocks: the RFC 1918 private blocks, 100.64.0.0/10 shared space, 127.0.0.0/8 loopback, 169.254.0.0/16 link-local, the three documentation /24 blocks and 224.0.0.0/4 multicast.
- Parse untrusted addresses with one strict parser: lenient parsers read
0x7f.1and010.1.2.3in ways people do not expect.
Terms in this lesson
- CIDR prefix
- The explicit length of the leading address bits that identify an IP address block.
- ordinary subnet hosts
- Addresses between the network and broadcast endpoints of an ordinary IPv4 subnet; point-to-point /31 and /32 contexts use different endpoint rules.
- wildcard mask
- The bitwise complement of a subnet mask within the 32-bit IPv4 address width.
References
- RFC 791: Internet Protocol (RFC Editor (IETF))
- RFC 4632: Classless Inter-domain Routing (CIDR): The Internet Address Assignment and Aggregation Plan (RFC Editor (IETF))
- RFC 3021: Using 31-Bit Prefixes on IPv4 Point-to-Point Links (RFC Editor (IETF))
- RFC 1122: Requirements for Internet Hosts, Communication Layers (RFC Editor (IETF))
- RFC 2644: Changing the Default for Directed Broadcasts in Routers (RFC Editor (IETF))
- RFC 1112: Host Extensions for IP Multicasting (RFC Editor (IETF))
- RFC 1918: Address Allocation for Private Internets (RFC Editor (IETF))
- RFC 6598: IANA-Reserved IPv4 Prefix for Shared Address Space (RFC Editor (IETF))
- RFC 3927: Dynamic Configuration of IPv4 Link-Local Addresses (RFC Editor (IETF))
- RFC 5737: IPv4 Address Blocks Reserved for Documentation (RFC Editor (IETF))
- RFC 6890: Special-Purpose IP Address Registries (RFC Editor (IETF))
- IANA IPv4 Special-Purpose Address Registry (Internet Assigned Numbers Authority (IANA))
- Free Pool of IPv4 Address Space Depleted (Number Resource Organization (NRO))
- inet_addr, inet_ntoa: IPv4 address manipulation (POSIX.1-2024) (The Open Group)
- URL Standard: IPv4 parser (WHATWG)
- ipaddress: IPv4/IPv6 manipulation library (Python Software Foundation)
- socket.inet_aton() (socket: Low-level networking interface) (Python Software Foundation)
- GATE 2027 syllabus: Computer Science and Information Technology (IIT Madras)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress