From ffcac67d9950f569573a76c6431243c6eb5f1671 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 13 Feb 2022 15:23:11 -0600 Subject: [PATCH] Add is_ipv4_address and is_ipv6_address utils (#66472) --- homeassistant/util/network.py | 20 ++++++++++++++++++++ tests/util/test_network.py | 16 ++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/homeassistant/util/network.py b/homeassistant/util/network.py index e714b6b6b31..396ab56b8c2 100644 --- a/homeassistant/util/network.py +++ b/homeassistant/util/network.py @@ -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("/")) diff --git a/tests/util/test_network.py b/tests/util/test_network.py index 089ef5e0ab8..b5c6b1a3e24 100644 --- a/tests/util/test_network.py +++ b/tests/util/test_network.py @@ -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"