You are implementing utilities to iterate over IPv4 addresses.
An IPv4 address is in dotted-decimal form: A.B.C.D, where each octet is an integer in [0, 255]. Conceptually, an IP can be treated as an unsigned 32-bit integer:
Implement a Python class IPv4Iterator(start_ip: str) that iterates forward from start_ip (inclusive) up to 255.255.255.255 (inclusive).
__init__
,
__iter__
,
__next__
.
__next__()
returns the next IP as a dotted string.
StopIteration
.
Example:
start_ip = "192.168.0.1"
"192.168.0.1"
,
"192.168.0.2"
, ... ,
"255.255.255.255"
Implement a reverse iterator IPv4ReverseIterator(end_ip: str) that iterates backward from end_ip (inclusive) down to 0.0.0.0 (inclusive).
Example:
end_ip = "192.168.0.255"
"192.168.0.255"
,
"192.168.0.254"
, ... ,
"0.0.0.0"
Given a CIDR string like "192.168.1.0/24", compute the start IP and end IP of the CIDR range using bitwise operations, then iterate through and return all IPs in that range (inclusive).
CIDR format: base_ip/prefix_len
base_ip
is a dotted IPv4 string.
prefix_len
is an integer
n
in
[0, 32]
meaning the first
n
bits are fixed (network bits) and the remaining
32-n
bits vary (host bits).
Requirements:
start_ip
(network address)
end_ip
(broadcast/highest address)
start_ip
to
end_ip
inclusive.
Example:
"192.168.1.0/24"
"192.168.1.0"
"192.168.1.255"
Discuss how you would optimize time and space complexity for the above tasks, especially for large CIDR ranges (e.g., /8 or /0).
255.255.255.255
, ending at
0.0.0.0
).