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
This commit is contained in:
Derek Higgins 2017-08-18 11:45:22 +01:00
parent d856fa44dc
commit 785b33c295
2 changed files with 18 additions and 0 deletions

View File

@ -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.

View File

@ -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'))