diff --git a/oslo_utils/netutils.py b/oslo_utils/netutils.py index e24f9188..26e16dc7 100644 --- a/oslo_utils/netutils.py +++ b/oslo_utils/netutils.py @@ -217,6 +217,20 @@ def is_ipv6_enabled(): return _IS_IPV6_ENABLED +def escape_ipv6(address): + """Escape an IP address in square brackets if IPv6 + + :param address: address to optionaly escape + :type address: string + :returns: string + + .. versionadded:: 3.29.0 + """ + if is_valid_ipv6(address): + return "[%s]" % address + return address + + def is_valid_ip(address): """Verify that address represents a valid IP address. diff --git a/oslo_utils/tests/test_netutils.py b/oslo_utils/tests/test_netutils.py index bba7c546..856b6718 100644 --- a/oslo_utils/tests/test_netutils.py +++ b/oslo_utils/tests/test_netutils.py @@ -172,6 +172,10 @@ class NetworkUtilsTest(test_base.BaseTestCase): self.assertFalse(netutils.is_valid_ipv6('')) + def test_escape_ipv6(self): + self.assertEqual('[1234::1234]', netutils.escape_ipv6('1234::1234')) + self.assertEqual('127.0.0.1', netutils.escape_ipv6('127.0.0.1')) + def test_is_valid_ip(self): self.assertTrue(netutils.is_valid_ip('127.0.0.1'))