Skip to content

Commit d500a32

Browse files
committed
Fix _normalize_ip_key to properly normalize IP addresses
Use ipaddress module instead of socket.inet_pton so that network host bits are zeroed (e.g. 192.168.1.100/24 → 192.168.1.0/24) and IPv6 addresses are compressed (e.g. 2001:0db8:0000:… → 2001:db8::1). https://claude.ai/code/session_01M3wRX9tnmc4qorVWRjmqTZ
1 parent 0ec76cf commit d500a32

File tree

1 file changed

+7
-12
lines changed

1 file changed

+7
-12
lines changed

src/ipdata/iptrie.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
from __future__ import annotations
1717

1818
import ipaddress
19-
import socket
2019
from collections.abc import Iterator
2120
from typing import TypeVar, Generic
2221

@@ -53,18 +52,14 @@ def _normalize_ip_key(key: str) -> tuple[str, bool]:
5352
if not key:
5453
raise InvalidIPError("Key cannot be empty")
5554

56-
addr = key.rsplit("/", 1)[0] if "/" in key else key
57-
58-
try:
59-
socket.inet_pton(socket.AF_INET, addr)
60-
return key, False
61-
except socket.error:
62-
pass
63-
6455
try:
65-
socket.inet_pton(socket.AF_INET6, addr)
66-
return key, True
67-
except socket.error:
56+
if "/" in key:
57+
network = ipaddress.ip_network(key, strict=False)
58+
return str(network), isinstance(network, ipaddress.IPv6Network)
59+
else:
60+
addr = ipaddress.ip_address(key)
61+
return str(addr), isinstance(addr, ipaddress.IPv6Address)
62+
except ValueError:
6863
raise InvalidIPError(f"Invalid IP address or network: {key!r}")
6964

7065

0 commit comments

Comments
 (0)