Created
December 19, 2024 03:06
-
-
Save shmick/e1fe8398564e311b78c05aca3e34fc88 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ipaddress | |
from typing import List, Tuple | |
cidr_blocks = [ | |
"172.31.0.0/16", ...... | |
] | |
def check_cidr_conflicts(cidr_blocks: List[str]) -> List[Tuple[str, List[str]]]: | |
results = [] | |
for i, cidr1 in enumerate(cidr_blocks): | |
conflicts = [] | |
try: | |
net1 = ipaddress.ip_network(cidr1) | |
# Check against all other CIDR blocks | |
for j, cidr2 in enumerate(cidr_blocks): | |
if i != j: | |
try: | |
net2 = ipaddress.ip_network(cidr2) | |
if net1.overlaps(net2): | |
conflicts.append(cidr2) | |
except ValueError: | |
continue | |
results.append((cidr1, conflicts)) | |
except ValueError as e: | |
results.append((cidr1, [f"Invalid CIDR block: {str(e)}"])) | |
return results | |
def print_conflict_report(results: List[Tuple[str, List[str]]]) -> None: | |
print("\nCIDR Block Overlap Analysis (in original order):") | |
print("-" * 50) | |
for cidr, conflicts in results: | |
if isinstance(conflicts, list) and conflicts and conflicts[0].startswith("Invalid"): | |
print(f"\nCIDR: {cidr}") | |
print(conflicts[0]) | |
else: | |
print(f"\nCIDR: {cidr}") | |
if conflicts: | |
print("Conflicts with:") | |
for conflict in conflicts: | |
print(f" - {conflict}") | |
else: | |
print("No conflicts found") | |
# Summary statistics | |
total_cidrs = len(results) | |
invalid_cidrs = sum(1 for _, conflicts in results if conflicts and isinstance(conflicts[0], str) and conflicts[0].startswith("Invalid")) | |
valid_cidrs = total_cidrs - invalid_cidrs | |
cidrs_with_conflicts = sum(1 for _, conflicts in results if conflicts and not (isinstance(conflicts[0], str) and conflicts[0].startswith("Invalid"))) | |
print("\nSummary:") | |
print(f"Total CIDR blocks analyzed: {total_cidrs}") | |
print(f"Valid CIDR blocks: {valid_cidrs}") | |
print(f"Invalid CIDR blocks: {invalid_cidrs}") | |
print(f"CIDR blocks with conflicts: {cidrs_with_conflicts}") | |
print(f"CIDR blocks without conflicts: {valid_cidrs - cidrs_with_conflicts}") | |
def main(): | |
try: | |
# Check for conflicts while maintaining original order | |
results = check_cidr_conflicts(cidr_blocks) | |
# Print detailed report | |
print_conflict_report(results) | |
except Exception as e: | |
print(f"An error occurred: {str(e)}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment