You need to implement an IPv4 iterator class in Python that can iterate through IP addresses. The problem progressively adds complexity through multiple parts, starting with forward iteration, then backward iteration, and finally adding CIDR support.
Implement an IPv4Iterator class in Python that can iterate through a range of IP addresses. The class should support the following functionalities:
The class should have the following methods:
__init__(self, start_ip, end_ip, cidr=None): Initialize the iterator with the start and end IP addresses. If cidr is provided, use it to determine the range of IP addresses.__iter__(self): Return the iterator object itself.__next__(self): Return the next IP address in the range. If the end of the range is reached, raise a StopIteration exception.`python
iterator = IPv4Iterator("192.168.1.1", "192.168.1.10") for ip in iterator: print(ip)
iterator = IPv4Iterator("192.168.1.10", "192.168.1.1") for ip in iterator: print(ip)
iterator = IPv4Iterator("192.168.1.0", "192.168.1.255", "192.168.1.0/24") for ip in iterator: print(ip) `
cidr parameter is optional and should only be used if provided.ipaddress module in Python for CIDR support.`python import ipaddress
class IPv4Iterator: def init(self, start_ip, end_ip, cidr=None): self.start_ip = ipaddress.IPv4Address(start_ip) self.end_ip = ipaddress.IPv4Address(end_ip) self.cidr = cidr self.current_ip = self.start_ip
def __iter__(self):
return self
def __next__(self):
if self.cidr:
network = ipaddress.IPv4Network(self.cidr, strict=False)
if self.current_ip not in network:
raise StopIteration
elif self.current_ip > self.end_ip:
raise StopIteration
result = str(self.current_ip)
self.current_ip += 1
return result
iterator = IPv4Iterator("192.168.1.1", "192.168.1.10") for ip in iterator: print(ip) `