Match IP Address to Network Block
Math & Bit ManipulationAuto-graded · 22 test casesLast updated
Tests bitwise operations on IPv4 addresses, CIDR prefix matching, and linear search with early termination.
You are building a network router utility that needs to determine which network block an IP address belongs to.
Given a target IPv4 address and a list of network blocks in CIDR notation, identify which block contains the target address. If multiple blocks match, return the earliest one in the list. If no block matches, return None.
IPv4 and CIDR Notation
An IPv4 address consists of four decimal numbers (0-255) separated by dots, for example "192.168.1.5".
A CIDR block is written as "base_address/prefix_length", where:
base_addressis an IPv4 addressprefix_lengthis an integer from 0 to 32
The CIDR block represents all IP addresses whose first prefix_length bits match the first prefix_length bits of the base address.
For example:
"192.168.0.0/16"includes all addresses from192.168.0.0to192.168.255.255"10.0.0.0/8"includes all addresses from10.0.0.0to10.255.255.255"0.0.0.0/0"includes all possible IPv4 addresses"192.168.1.5/32"includes only the exact address192.168.1.5
Input Format
ip: A string representing a valid IPv4 addresscidr_blocks: A list of strings, each representing a valid CIDR block
Output Format
Return the first CIDR block string from the list that contains the given IP address, or None if no block contains it.
Constraints
- All input strings are guaranteed to be syntactically valid
1 ≤ len(cidr_blocks) ≤ 100,000- Each octet in an IPv4 address satisfies
0 ≤ octet ≤ 255 - Each prefix length satisfies
0 ≤ prefix_length ≤ 32 - The base address in a CIDR block may have non-zero host bits (bits beyond the prefix)
Examples
Example 1
Input: match_ip_to_network('192.168.1.5', ['10.0.0.0/8', '192.168.0.0/16', '192.168.1.0/24'])
Output: '192.168.0.0/16'
Example 2
Input: match_ip_to_network('192.168.1.5', ['192.168.2.0/24', '192.168.1.128/25'])
Output: None
Example 3
Input: match_ip_to_network('8.8.8.8', ['0.0.0.0/0'])
Output: '0.0.0.0/0'
Example 4
Input: match_ip_to_network('172.16.4.9', ['172.16.0.0/12', '172.16.4.0/24', '172.0.0.0/8'])
Output: '172.16.0.0/12'
Hints
Hint 1
Convert each IPv4 address to a 32-bit integer by treating each octet as 8 bits
Hint 2
Create a bitmask with the first prefix_length bits set to 1 and the rest set to 0
Hint 3
An IP matches a CIDR block when (ip & mask) equals (base & mask)
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to treat IPv4 addresses as 32-bit unsigned integers and use bitwise operations to check prefix matching.
Converting IP to Integer
Each IPv4 address can be represented as a 32-bit number where each octet occupies 8 bits. For "192.168.1.5":
- Start with 0
- Shift left 8 bits and add 192:
192 - Shift left 8 bits and add 168:
49320 - Shift left 8 bits and add 1:
12625921 - Shift left 8 bits and add 5:
3232235781
This gives us: 192 << 24 | 168 << 16 | 1 << 8 | 5
Creating the Prefix Mask
A CIDR prefix of length x means we only care about the first x bits. We create a mask by:
- Starting with all ones:
0xFFFFFFFF - Shifting left by
(32 - x)positions to createxleading ones - Masking with
0xFFFFFFFFto ensure we stay within 32 bits
Special case: when x = 0, the mask is 0 (matches everything).
Matching Logic
An IP address belongs to a CIDR block when the masked bits of both the IP and the base address are identical:
(ip_as_int & mask) == (base_as_int & mask)
We mask both sides because the base address might have non-zero host bits that should be ignored.
Finding the First Match
Scan through the CIDR blocks in order and return the first one that matches. This ensures we respect list order rather than finding the most specific match.
Correctness
- Bit representation: Left-shifting and OR-ing octets correctly positions each byte in big-endian order
- Mask construction: The shift-and-truncate approach handles all prefix lengths including edge cases
/0and/32 - Two-sided masking: Applying the mask to both the target IP and base address ensures host bits in the base don't affect the comparison
- Early termination: Returning immediately upon finding a match guarantees the first occurrence in list order
Complexity
Time: O(n) where n is the number of CIDR blocks. Each block requires constant-time operations: splitting a string, parsing 4 integers, and performing bitwise comparisons.
Space: O(1) additional space beyond the input. String splitting creates temporary objects but these are bounded by constant factors.
For 100,000 blocks, this approach completes in well under a second.
from typing import List, Optional
def _parse_ip(ip: str) -> int:
result = 0
for octet in ip.split('.'):
result = (result << 8) | int(octet)
return result
def match_ip_to_network(ip: str, cidr_blocks: List[str]) -> Optional[str]:
target = _parse_ip(ip)
for block in cidr_blocks:
base_str, prefix_str = block.split('/')
prefix_len = int(prefix_str)
base = _parse_ip(base_str)
if prefix_len == 0:
mask = 0
else:
mask = (0xffffffff << (32 - prefix_len)) & 0xffffffff
if (target & mask) == (base & mask):
return block
return None