KatInterview

Match IP Address to Network Block

Math & Bit ManipulationAuto-graded · 22 test cases
MediumAuto-gradedMath & Bit Manipulationbit-manipulationipv4networking

Last 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_address is an IPv4 address
  • prefix_length is 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 from 192.168.0.0 to 192.168.255.255
  • "10.0.0.0/8" includes all addresses from 10.0.0.0 to 10.255.255.255
  • "0.0.0.0/0" includes all possible IPv4 addresses
  • "192.168.1.5/32" includes only the exact address 192.168.1.5

Input Format

  • ip: A string representing a valid IPv4 address
  • cidr_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)