Subnets

What is a subnet?

TL;DR: a contiguous subset of IP addresses within a network.

A subnet is a subset of IPs within a given network. Specifically, it is a subset of IPs where each IP address shares a prefix.

For example, the subnet mask 192.168.0.0/24 represents the set of IP addresses in the range 192.168.0.0 to 192.168.0.255.

The subnet mask representation has two components: an IP address (192.168.0.0) and a mask /24. The number in the mask represents the number of bits on the left hand side of the IP address (i.e. the most significant bits) which do not change (i.e. they form the shared prefix).

NOTE: multiple subnet masks can represent the same set of IP addresses. e.g. 192.168.0.0/24 is the same as 192.168.0.192/24

Why do we need subnets?

TL;DR: more efficient for routing purposes.

An IP address provides a means of identifying a machine on a network, allowing for communication with that machine via the IP protocol. In order to identify the same machine reliably, the IP address must be unique within a given network.

For a local network, this is quite simple. Say we have a router which has one means of ingesting data, and a direct ethernet connection to 3 machines which have been assigned the IP addresses 192.168.0.1, 192.168.0.2 and 192.168.0.3.

The router can maintain a table pairing IP addresses with ports to communicate on:

IP Address Outbound Port
192.168.0.1 1
192.168.0.2 2
192.168.0.3 3

If the router now recieves a packet targetting IP address 192.168.0.1, it can perform a direct lookup in the table which will tell it to forward the packet on port 1.

There is, however, a problem with this approach. It does not scale to a large network. Say we had 1 million machines on our network, the table look up now requires more memory and more time. Remember, this is implemented in hardware because networking needs to be fast.

Let's, then imagine a larger network, with two layers of router between the leaf nodes and the rest of the network.

Now, we could maintain a table of each IP address to the relevant port, but this quickly becomes inefficient as we add layers of routing.
It would be more efficient to define routes for subnets with subnet masks.

For example, the routers could have the following tables:

Router A

IP Subnet Mask Outbound Port
192.168.1.0/24 1
192.168.2.0/24 2
192.168.3.0/24 3

Router B

IP Subnet Mask Outbound Port
192.168.1.1/32 1
192.168.1.2/32 2
192.168.1.3/32 3

Router C

IP Subnet Mask Outbound Port
192.168.2.1/32 1
192.168.2.2/32 2
192.168.2.3/32 3

Router D

IP Subnet Mask Outbound Port
192.168.3.1/32 1
192.168.3.2/32 2
192.168.3.3/32 3

This means that A only needs to maintain enough information to determine the next hop, and can direct one (or just a handful) of entries to any particular port.