KatInterview

Build an IP Address Calculator Without Libraries

Math & Bit ManipulationModel answer
HardModel answerMath & Bit Manipulationbit-manipulationparsingnetworking

Last updated

Create a utility to parse, compute offsets, and analyze CIDR blocks for IPv4 and IPv6 addresses using integer arithmetic, no networking libraries allowed.

Problem

Build a calculator that handles IPv4 and IPv6 addresses and subnet blocks. You cannot use any built-in networking modules (no ipaddress, no socket.inet_pton, no urllib).

Implement these three operations:

1. add_offset(ip: str, offset: int) -> str

Take an IP address string and shift it by an integer offset (positive or negative). Return the result in canonical format.

If the result goes below zero or exceeds the maximum address for that version (2³² - 1 for IPv4, 2¹²⁸ - 1 for IPv6), raise ValueError.

2. cidr_info(cidr: str) -> tuple[str, str, int]

Parse a subnet in CIDR notation (like "10.0.0.0/8" or "fe80::/10") and return:

  • The first address in the range (network address)
  • The last address in the range (broadcast address)
  • The total count of addresses in the range

All addresses must be in canonical string form.

3. contains(cidr: str, ip: str) -> bool

Check whether an IP address falls inside a CIDR block. Return True if it does, False otherwise.

If the IP version doesn't match the CIDR block version, raise ValueError.


Canonical Format Rules

IPv4: Four decimal numbers (0–255) separated by dots. No leading zeros in any segment unless the segment is exactly "0".

Example: "192.0.2.1" ✓ "192.000.002.001" ✗

IPv6 (RFC 5952):

  • Eight groups of up to four lowercase hex digits, separated by colons
  • Omit leading zeros within each group (:0001: becomes :1:)
  • Replace the longest sequence of consecutive all-zero groups with :: (only once)
  • If multiple sequences tie for longest, compress the first one
  • A single zero group should not be compressed

Examples:

  • "2001:db8::1" ✓
  • "2001:0db8:0000:0000:0000:0000:0000:0001" ✗ (not compressed)
  • "fe80:0:0:0:1::" should be "fe80::1:0:0:0" (compress first run on tie)

Interface

class IPArithmetic:
    def add_offset(self, ip: str, offset: int) -> str:
        pass

    def cidr_info(self, cidr: str) -> tuple[str, str, int]:
        pass

    def contains(self, cidr: str, ip: str) -> bool:
        pass

Examples

calc = IPArithmetic()

# IPv4 offset
calc.add_offset("10.0.0.255", 1)
# → "10.0.1.0"

# IPv4 CIDR
calc.cidr_info("172.16.0.0/12")
# → ("172.16.0.0", "172.31.255.255", 1048576)

# IPv4 membership
calc.contains("192.168.0.0/16", "192.168.5.100")
# → True

# IPv6 offset
calc.add_offset("2001:db8::", 256)
# → "2001:db8::100"

# IPv6 CIDR
calc.cidr_info("2001:db8::/32")
# → ("2001:db8::", "2001:db8:ffff:ffff:ffff:ffff:ffff:ffff", 79228162514264337593543950336)

# Overflow
calc.add_offset("255.255.255.255", 1)
# → raises ValueError

Constraints

  • IPv4 prefix: 0 ≤ prefix ≤ 32
  • IPv6 prefix: 0 ≤ prefix ≤ 128
  • Offset can be any integer within reasonable bounds
  • No external networking libraries allowed

Hints

Hint 1

Convert addresses to integers, do arithmetic in integer space, then convert back to strings

Hint 2

For CIDR: create masks by shifting bits, apply them to find network and broadcast boundaries

Hint 3

IPv6 compression: find the longest run of zero groups, replace it with :: (ties go to the first occurrence)