From 785b33c29542639680659b1d68d9047df5af2964 Mon Sep 17 00:00:00 2001 From: Derek Higgins Date: Fri, 18 Aug 2017 11:45:22 +0100 Subject: [PATCH] Add method to escape ipv6 ip addresses IPv6 addresses are commonly enclosed in square brackets in resource identifiers to allow them to be distinguished from port numbers. I've come accross the need of this in multiple places zaqar https://review.openstack.org/#/c/495279 tripleo https://review.openstack.org/#/c/494440 ironic https://review.openstack.org/#/c/411809 ironic-python-agent https://review.openstack.org/#/c/411817 Change-Id: Icdcf681c1d71a09b88b029f80d13cd5015dacd56 --- oslo_utils/netutils.py | 14 ++++++++++++++ oslo_utils/tests/test_netutils.py | 4 ++++ 2 files changed, 18 insertions(+) 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'))