Build an IP Address Calculator Without Libraries
Math & Bit ManipulationModel answerLast 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)
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to treat every address as an unsigned integer: 32 bits for IPv4, 128 bits for IPv6. All arithmetic, masking, and comparison happens on these integers. Strings are only converted at the input and output boundaries.
High-Level Strategy
-
Parse: Convert string →
(integer_value, bit_width)- Detect IPv4 vs IPv6 by checking for colons
- IPv4: split on
., validate four octets, pack into 32 bits - IPv6: handle
::expansion, validate hextets, pack into 128 bits
-
Arithmetic: Work with integers
- Offset:
new_value = value + offset, then range-check - CIDR masking: compute network and broadcast using bit masks
- Offset:
-
Format: Convert integer → canonical string
- IPv4: extract four octets, join with dots
- IPv6: extract eight 16-bit groups, apply RFC 5952 compression
Parsing
IPv4
Split on . and require exactly four parts. Each part must:
- Contain only ASCII digits
0-9(not Unicode digit characters) - Have no leading zeros unless the part is
"0" - Be in range [0, 255]
Pack into 32 bits: (octet[0] << 24) | (octet[1] << 16) | (octet[2] << 8) | octet[3]
IPv6
Handle the :: shorthand:
- If
::appears (at most once), split on it into left and right segments - Parse each segment as colon-separated hex groups (1–4 hex digits each)
- Insert
8 - len(left) - len(right)zero groups in the middle (must be ≥1) - Without
::, require exactly 8 groups
Pack into 128 bits by shifting and ORing each 16-bit group.
Reject malformed input like :::, empty groups (unless from splitting "::"), or >8 total groups.
Formatting
IPv4
Extract four octets: (value >> shift) & 0xFF for shifts 24, 16, 8, 0. Join with dots.
IPv6 (RFC 5952)
- Extract eight 16-bit groups:
(value >> (112 - 16*i)) & 0xFFFF - Find the longest consecutive run of all-zero groups using a single scan:
- Track
best_startandbest_len - Use strict
>(not>=) so ties keep the first run
- Track
- If
best_len ≥ 2:- Join groups before the run with
: - Insert
:: - Join groups after the run with
:
- Join groups before the run with
- Otherwise join all eight groups with
: - Format each group with lowercase hex, no leading zeros:
format(g, 'x')
The all-zero address correctly becomes "::".
CIDR Operations
A CIDR block like 192.168.1.0/24 represents all addresses sharing the top 24 bits.
Compute masks:
host_bits = bits - prefix
host_mask = (1 << host_bits) - 1 # all 1s in host portion
net_mask = ((1 << bits) - 1) ^ host_mask # all 1s in network portion
Network address: value & net_mask (clear host bits)
Broadcast address: network | host_mask (set host bits)
Count: 2^(bits - prefix) addresses in the block
Membership test: (ip_value & net_mask) == network
Edge Cases
- Carry across boundaries:
192.168.1.255 + 1 → 192.168.2.0works automatically with integer arithmetic - Overflow/underflow:
0.0.0.0 - 1andffff:...:ffff + 1raiseValueError - Extreme prefixes:
/0covers the entire address space (2³² or 2¹²⁸ addresses)/32and/128are single addresses (network = broadcast)
- CIDR with host bits set (e.g.,
192.168.1.5/24): mask it down to the network address - Zero-run ties:
1:0:0:2:0:0:0:3has two runs of length 2; compress the first →1::2:0:0:0:3 - Single zero group:
2001:db8:0:1::keeps the lone zero (no compression for length 1) - Version mismatch:
contains("10.0.0.0/8", "::1")raisesValueError
Complexity
Time: O(L) where L is input length. For addresses, L is bounded (~15 for IPv4, ~39 for IPv6), so effectively O(1). Formatting scans fixed-size groups (4 or 8).
Space: O(1) aside from the parsed group list and output string.
Implementation
class IPArithmetic:
_DIGITS = set("0123456789")
_HEX = set("0123456789abcdefABCDEF")
def _parse_ipv4(self, s: str) -> int:
parts = s.split(".")
if len(parts) != 4:
raise ValueError(f"IPv4 needs 4 octets: {s!r}")
value = 0
for part in parts:
if not part or not all(c in self._DIGITS for c in part):
raise ValueError(f"Invalid octet: {part!r}")
if len(part) > 1 and part[0] == "0":
raise ValueError(f"Leading zero: {part!r}")
n = int(part)
if n > 255:
raise ValueError(f"Octet > 255: {part!r}")
value = (value << 8) | n
return value
def _parse_hex_groups(self, segment: str) -> list[int]:
if not segment:
return []
groups = []
for g in segment.split(":"):
if not (1 <= len(g) <= 4) or not all(c in self._HEX for c in g):
raise ValueError(f"Invalid hextet: {g!r}")
groups.append(int(g, 16))
return groups
def _parse_ipv6(self, s: str) -> int:
if s.count("::") > 1:
raise ValueError(f"Multiple '::': {s!r}")
if "::" in s:
left_str, right_str = s.split("::")
left = self._parse_hex_groups(left_str)
right = self._parse_hex_groups(right_str)
if len(left) + len(right) > 7:
raise ValueError(f"Too many groups: {s!r}")
groups = left + [0] * (8 - len(left) - len(right)) + right
else:
groups = self._parse_hex_groups(s)
if len(groups) != 8:
raise ValueError(f"IPv6 needs 8 groups: {s!r}")
value = 0
for g in groups:
value = (value << 16) | g
return value
def _parse_ip(self, ip: str) -> tuple[int, int]:
if ":" in ip:
return self._parse_ipv6(ip), 128
return self._parse_ipv4(ip), 32
def _parse_cidr(self, cidr: str) -> tuple[int, int, int]:
parts = cidr.split("/")
if len(parts) != 2:
raise ValueError(f"CIDR needs address/prefix: {cidr!r}")
addr_str, prefix_str = parts
value, bits = self._parse_ip(addr_str)
if not prefix_str or not all(c in self._DIGITS for c in prefix_str):
raise ValueError(f"Invalid prefix: {prefix_str!r}")
prefix = int(prefix_str)
if prefix > bits:
raise ValueError(f"Prefix {prefix} > {bits}")
return value, bits, prefix
def _format_ipv4(self, value: int) -> str:
return ".".join(str((value >> shift) & 0xFF) for shift in (24, 16, 8, 0))
def _format_ipv6(self, value: int) -> str:
groups = [(value >> (112 - 16 * i)) & 0xFFFF for i in range(8)]
# Find longest run of zeros
best_start, best_len = -1, 0
i = 0
while i < 8:
if groups[i] == 0:
j = i
while j < 8 and groups[j] == 0:
j += 1
if j - i > best_len:
best_start, best_len = i, j - i
i = j
else:
i += 1
hex_groups = [format(g, "x") for g in groups]
if best_len >= 2:
left = ":".join(hex_groups[:best_start])
right = ":".join(hex_groups[best_start + best_len:])
return f"{left}::{right}"
return ":".join(hex_groups)
def _format(self, value: int, bits: int) -> str:
if bits == 32:
return self._format_ipv4(value)
return self._format_ipv6(value)
def _compute_masks(self, bits: int, prefix: int) -> tuple[int, int]:
host_bits = bits - prefix
host_mask = (1 << host_bits) - 1
net_mask = ((1 << bits) - 1) ^ host_mask
return net_mask, host_mask
def add_offset(self, ip: str, offset: int) -> str:
value, bits = self._parse_ip(ip)
result = value + offset
max_value = (1 << bits) - 1
if not (0 <= result <= max_value):
raise ValueError(f"Result out of range for {bits}-bit address")
return self._format(result, bits)
def cidr_info(self, cidr: str) -> tuple[str, str, int]:
value, bits, prefix = self._parse_cidr(cidr)
net_mask, host_mask = self._compute_masks(bits, prefix)
network = value & net_mask
broadcast = network | host_mask
total = 1 << (bits - prefix)
return (
self._format(network, bits),
self._format(broadcast, bits),
total
)
def contains(self, cidr: str, ip: str) -> bool:
cidr_value, cidr_bits, prefix = self._parse_cidr(cidr)
ip_value, ip_bits = self._parse_ip(ip)
if cidr_bits != ip_bits:
raise ValueError(f"Version mismatch: CIDR is IPv{cidr_bits//32*4}, IP is IPv{ip_bits//32*4}")
net_mask, _ = self._compute_masks(cidr_bits, prefix)
network = cidr_value & net_mask
return (ip_value & net_mask) == network
This solution handles all edge cases, follows RFC 5952 for IPv6 canonicalization, and performs all operations using pure integer arithmetic without networking libraries.