Add is_ipv4_address and is_ipv6_address utils (#66472)

This commit is contained in:
J. Nick Koston 2022-02-13 15:23:11 -06:00 committed by GitHub
parent 2bdf55465a
commit ffcac67d99
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 0 deletions

View File

@ -59,6 +59,26 @@ def is_ip_address(address: str) -> bool:
return True
def is_ipv4_address(address: str) -> bool:
"""Check if a given string is an IPv4 address."""
try:
IPv4Address(address)
except ValueError:
return False
return True
def is_ipv6_address(address: str) -> bool:
"""Check if a given string is an IPv6 address."""
try:
IPv6Address(address)
except ValueError:
return False
return True
def normalize_url(address: str) -> str:
"""Normalize a given URL."""
url = yarl.URL(address.rstrip("/"))

View File

@ -56,6 +56,22 @@ def test_is_ip_address():
assert not network_util.is_ip_address("example.com")
def test_is_ipv4_address():
"""Test if strings are IPv4 addresses."""
assert network_util.is_ipv4_address("192.168.0.1") is True
assert network_util.is_ipv4_address("8.8.8.8") is True
assert network_util.is_ipv4_address("192.168.0.999") is False
assert network_util.is_ipv4_address("192.168.0.0/24") is False
assert network_util.is_ipv4_address("example.com") is False
def test_is_ipv6_address():
"""Test if strings are IPv6 addresses."""
assert network_util.is_ipv6_address("::1") is True
assert network_util.is_ipv6_address("8.8.8.8") is False
assert network_util.is_ipv6_address("8.8.8.8") is False
def test_normalize_url():
"""Test the normalizing of URLs."""
assert network_util.normalize_url("http://example.com") == "http://example.com"