mediumNetwork securityWeb security
IP Address in CIDR Range
Decide whether an IPv4 address falls inside a CIDR block such as 10.0.0.0/8, the check behind firewall rules, allow-lists and SSRF protection.
JavaScript or Python
Firewall rules, cloud security groups and SSRF defences all ask the same question: is this address inside that network? Given an IPv4 address ip such as "192.168.1.20" and a block in CIDR notation cidr such as "192.168.1.0/24", return true if the address is inside the block.
The prefix length is between 0 and 32. The network part of the CIDR may have host bits set (for example "10.1.2.3/8"); only the first prefix bits matter.
Examples
Example 1
Input: ip = "192.168.1.20", cidr = "192.168.1.0/24" Output: true Why: The first 24 bits match
Example 2
Input: ip = "192.168.2.1", cidr = "192.168.1.0/24" Output: false Why: The third octet differs
Constraints
- Addresses are valid dotted IPv4
0 <= prefix <= 32
Hints
Hint 1
Turn each address into a 32-bit number: multiply by 256 and add each octet.
Hint 2
Two addresses share the first p bits when they are equal after dividing by 2^(32 - p) and rounding down.
Solution
Show the solution (try it yourself first)
Convert both addresses to integers, then compare only the network bits. Dividing by 2^(32 - prefix) and flooring drops the host bits, which avoids JavaScript's signed 32-bit bitwise operators: /0 matches everything and /32 needs an exact match.
def ip_in_cidr(ip, cidr):
def to_int(addr):
n = 0
for part in addr.split("."):
n = n * 256 + int(part)
return n
network, prefix = cidr.split("/")
block = 2 ** (32 - int(prefix))
return to_int(ip) // block == to_int(network) // blockComplexity
O(1) time and space. In production use a tested library (Python's ipaddress, or a vetted package) that also handles IPv6, and for SSRF protection resolve the hostname first and check the resolved address against private and link-local ranges such as 10.0.0.0/8, 127.0.0.0/8 and 169.254.0.0/16, re-checking after redirects. Attackers often use alternative notations, which is why parsing matters.
Found a mistake in this problem, its tests or the solution?