IP Subnet Masking with AND
Learn how routers use bitwise AND to apply subnet masks to IP addresses, determining network addresses and routing decisions.
Detailed Explanation
Subnet Masking with Bitwise AND
Routers determine which network an IP address belongs to by ANDing the address with a subnet mask. This is one of the most critical real-world applications of bitwise AND.
How Subnet Masks Work
A subnet mask has contiguous 1-bits (network portion) followed by contiguous 0-bits (host portion):
255.255.255.0 = 11111111.11111111.11111111.00000000 (/24)
255.255.240.0 = 11111111.11111111.11110000.00000000 (/20)
255.255.255.128 = 11111111.11111111.11111111.10000000 (/25)
Computing the Network Address
AND the IP address with the mask to get the network address:
IP: 192.168.1.100 = 11000000.10101000.00000001.01100100
Mask: 255.255.255.0 = 11111111.11111111.11111111.00000000
──────────────────────────────────────────────────────────────
Network: 192.168.1.0 = 11000000.10101000.00000001.00000000
A More Interesting Example (/20 Mask)
IP: 10.0.47.200 = 00001010.00000000.00101111.11001000
Mask: 255.255.240.0 = 11111111.11111111.11110000.00000000
──────────────────────────────────────────────────────────────
Network: 10.0.32.0 = 00001010.00000000.00100000.00000000
Notice how the AND operation zeroes out the host portion (last 12 bits), leaving only the network prefix.
Same-Network Check
Two hosts are on the same network if their ANDed results match:
function sameNetwork(ip1, ip2, mask) {
return (ip1 & mask) === (ip2 & mask);
}
Broadcast Address
The broadcast address has all host bits set to 1. Compute it with OR:
const broadcast = networkAddress | ~subnetMask;
// For /24: 192.168.1.0 | 0.0.0.255 = 192.168.1.255
Use Case
Every router on the internet performs subnet masking on every packet it forwards. When a packet arrives, the router ANDs the destination IP with each routing table entry's mask to find the longest prefix match. High-performance routers implement this in hardware using TCAM (Ternary Content-Addressable Memory) that performs thousands of AND-and-compare operations simultaneously in a single clock cycle.