← All Exercises

Test Address Membership in a CIDR Block

intermediatejavascript~25min

Background

Firewall and rate-limit rules are written in CIDR. Checking membership by hand produces off-by-one errors at the network and broadcast boundaries.

Problem

Convert a CIDR block and a list of IPv4 addresses to integers and report which addresses fall inside the block.

Input

JSON object: { cidr: "a.b.c.d/n", ipv4: string[] }

Output

JSON object: { inside: string[], outside: string[] }

Sample tests

Sample 1

Input: {"cidr":"10.0.0.0/24","ipv4":["10.0.0.5","10.0.1.5"]}
Expected: {"inside":["10.0.0.5"],"outside":["10.0.1.5"]}

Sample 2

Input: {"cidr":"192.168.0.0/22","ipv4":["192.168.1.10","192.168.4.10"]}
Expected: {"inside":["192.168.1.10"],"outside":["192.168.4.10"]}

Your solution

Learning objective

Verify CIDR membership with the same arithmetic firewalls use.