PIXELBANKv9.1.0
Menu

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:

Input:
print(in_cidr("10.0.5.9", "10.0.0.0/16"))
Output:
True
Reasoning:
  • Parse the CIDR string "10.0.0.0/16" to extract the network address 10.0.0.0 and the prefix length 1616.
  • Convert the IP address "10.0.5.9" and the network address "10.0.0.0" into 32-bit integers:
    • IP: 10â‹…2563+0â‹…2562+5â‹…256+9=16777344910 \cdot 256^3 + 0 \cdot 256^2 + 5 \cdot 256 + 9 = 167773449
    • Network: 10â‹…2563+0â‹…2562+0â‹…256+0=16777216010 \cdot 256^3 + 0 \cdot 256^2 + 0 \cdot 256 + 0 = 167772160
  • Construct the subnet mask with 1616 leading ones and 1616 trailing zeros, which equals 232−216=42949017602^{32} - 2^{16} = 4294901760 (or 0xFFFF00000xFFFF0000 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: 167773449&4294901760=167772160167773449 \& 4294901760 = 167772160
    • Network masked: 167772160&4294901760=167772160167772160 \& 4294901760 = 167772160
  • Compare the masked values; since 167772160==167772160167772160 == 167772160, 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.
  • prefix in 0..32.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Is an IP Inside a CIDR Block - Medium | PixelBank