Is an IP Inside a CIDR Block
Problem Statement
Determine whether an IPv4 address falls within a CIDR block.
Background
A CIDR network/prefix covers all addresses sharing the top prefix bits with the network address. Build a mask of prefix ones followed by 32-prefix zeros; the IP is in-range if (ip & mask) == (network & mask).
Your Task
def in_cidr(ip, cidr):
- ip: dotted-quad string.
- cidr: "network/prefix" string.
- Return True if ip is within the block.
Input Format
- ip (str), cidr (str).
Output Format
- A boolean.
Sample
print(in_cidr("10.0.5.9", "10.0.0.0/16"))
Output:
True
Example
print(in_cidr("10.0.5.9", "10.0.0.0/16"))True
- Parse the CIDR string
"10.0.0.0/16"to extract the network address10.0.0.0and the prefix length . - Convert the IP address
"10.0.5.9"and the network address"10.0.0.0"into 32-bit integers:- IP:
- Network:
- Construct the subnet mask with leading ones and trailing zeros, which equals (or in hex).
- Apply the bitwise AND operation to both the IP and the network address using the mask to isolate the network portion:
- IP masked:
- Network masked:
- Compare the masked values; since , the IP falls within the CIDR block.
- The final output is True
Constraints
- Mask =
(0xFFFFFFFF << (32-prefix)) & 0xFFFFFFFF. - In-range iff masked ip equals masked network.
prefixin0..32.