DEV Community

Cover image for Network Address Calculation: The Subnet Math That Matters
Mark Yu
Mark Yu

Posted on • Edited on

Network Address Calculation: The Subnet Math That Matters

Subnet math feels annoying until you need to debug a firewall rule, Kubernetes network policy, VPN route, or cloud security group.

Then suddenly this question matters:

Given an IP address and subnet mask, what network is it actually in?

Let’s calculate it directly.

The Rule

network address = IP address AND subnet mask
Enter fullscreen mode Exit fullscreen mode

That is it.

The AND operation compares bits:

IP bit Mask bit Result
0 0 0
0 1 0
1 0 0
1 1 1

Example: 192.168.10.37/24

/24 means the subnet mask is:

255.255.255.0
Enter fullscreen mode Exit fullscreen mode

IP:

192.168.10.37
Enter fullscreen mode Exit fullscreen mode

Mask:

255.255.255.0
Enter fullscreen mode Exit fullscreen mode

Network:

192.168.10.0
Enter fullscreen mode Exit fullscreen mode

With /24, the first three octets are the network part. The last octet is host space.

Example: 192.168.10.37/26

/26 is more interesting.

Mask:

255.255.255.192
Enter fullscreen mode Exit fullscreen mode

The last octet in binary:

IP:   37  = 00100101
Mask: 192 = 11000000
AND:       00000000
Enter fullscreen mode Exit fullscreen mode

So the network address is:

192.168.10.0/26
Enter fullscreen mode Exit fullscreen mode

The /26 networks in the last octet move in blocks of 64:

Network Host range
192.168.10.0/26 .1 - .62
192.168.10.64/26 .65 - .126
192.168.10.128/26 .129 - .190
192.168.10.192/26 .193 - .254

37 falls into the first block.

Quick Mental Shortcut

For masks in the last octet:

block size = 256 - mask_octet
Enter fullscreen mode Exit fullscreen mode

For /26:

256 - 192 = 64
Enter fullscreen mode Exit fullscreen mode

So networks start at:

0, 64, 128, 192
Enter fullscreen mode Exit fullscreen mode

Find the block that contains the IP.

Python Check

import ipaddress

ip = ipaddress.ip_interface("192.168.10.37/26")
print(ip.network)
Enter fullscreen mode Exit fullscreen mode

Output:

192.168.10.0/26
Enter fullscreen mode Exit fullscreen mode

This is what I use when I do not want to trust my tired brain during network debugging.

Why Developers Should Care

Subnet mistakes show up in:

  • cloud VPC rules
  • Docker/Kubernetes networking
  • VPN routing
  • database allowlists
  • office network debugging
  • zero-trust access rules

One wrong CIDR can expose too much or block the service you need.

Final Thought

Subnetting is not glamorous, but it is one of those fundamentals that saves time when production networking gets weird.

What subnet or CIDR mistake has bitten you before?

Top comments (0)