Skip to content

Commit 69f235c

Browse files
committed
is_private_ip: Use IPMatcher
1 parent 9671b29 commit 69f235c

1 file changed

Lines changed: 7 additions & 33 deletions

File tree

Lines changed: 7 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
"""Only exports is_private_ip function"""
2-
3-
import ipaddress
1+
from aikido_zen.helpers.ip_matcher import IPMatcher
2+
from aikido_zen.helpers.ip_matcher.map_ipv4_to_ipv6 import map_ipv4_to_ipv6
43

54
# Define private IP ranges
65
PRIVATE_IP_RANGES = [
@@ -35,40 +34,15 @@
3534
"3fff::/20", # Documentation prefix (RFC 9637)
3635
]
3736

38-
# Create a set to hold private IP networks
39-
private_ip_networks = set()
37+
private_ip_list = IPMatcher()
4038

41-
# Add private IPv4 ranges to the set
4239
for ip_range in PRIVATE_IP_RANGES:
43-
private_ip_networks.add(ipaddress.ip_network(ip_range))
44-
45-
# Add private IPv6 ranges to the set
40+
private_ip_list.add(ip_range)
41+
private_ip_list.add(map_ipv4_to_ipv6(ip_range))
4642
for ip_range in PRIVATE_IPV6_RANGES:
47-
private_ip_networks.add(ipaddress.ip_network(ip_range))
48-
49-
50-
def normalize_ip(ip):
51-
"""Normalize the IP address by removing leading zeros."""
52-
if not ":" in ip:
53-
# Normalize IPv4 ip's
54-
parts = ip.split(".")
55-
normalized_parts = [
56-
str(int(part)) for part in parts
57-
] # Convert to int and back to str to remove leading zeros
58-
return ".".join(normalized_parts)
59-
return ip
43+
private_ip_list.add(ip_range)
6044

6145

6246
def is_private_ip(ip):
6347
"""Returns true if the ip entered is private"""
64-
try:
65-
normalized_ip = normalize_ip(ip)
66-
ip_obj = ipaddress.ip_address(normalized_ip)
67-
if isinstance(ip_obj, ipaddress.IPv6Address) and ip_obj.ipv4_mapped:
68-
# If it's an IPv4-mapped IPv6 addresses, check if the IPv4 address is in any of the private networks
69-
return any(ip_obj.ipv4_mapped in network for network in private_ip_networks)
70-
71-
# Check if the IP address is in any of the private networks
72-
return any(ip_obj in network for network in private_ip_networks)
73-
except ValueError:
74-
return False # Return False if the IP address is invalid
48+
return private_ip_list.has(ip)

0 commit comments

Comments
 (0)