diff --git a/oslo/utils/netutils.py b/oslo/utils/netutils.py index d054c66..6bc9acf 100644 --- a/oslo/utils/netutils.py +++ b/oslo/utils/netutils.py @@ -114,6 +114,16 @@ def is_valid_ip(address): return is_valid_ipv4(address) or is_valid_ipv6(address) +def is_valid_port(port): + """Verify that port represents a valid port number.""" + try: + val = int(port) + except (ValueError, TypeError): + return False + + return (val > 0 and val <= 65535) + + def get_my_ipv4(): """Returns the actual ipv4 of the local machine. diff --git a/tests/test_netutils.py b/tests/test_netutils.py index cd4b23a..3ed240d 100644 --- a/tests/test_netutils.py +++ b/tests/test_netutils.py @@ -178,6 +178,18 @@ class NetworkUtilsTest(test_base.BaseTestCase): self.assertFalse(netutils.is_valid_ip('')) + def test_valid_port(self): + valid_inputs = [1, '1', 2, '3', '5', 8, 13, 21, + '80', '3246', '65535'] + for input_str in valid_inputs: + self.assertTrue(netutils.is_valid_port(input_str)) + + def test_valid_port_fail(self): + invalid_inputs = ['-32768', '0', 0, '65536', 528491, '528491', + '528.491', 'thirty-seven', None] + for input_str in invalid_inputs: + self.assertFalse(netutils.is_valid_port(input_str)) + def test_get_my_ip(self): sock_attrs = { 'return_value.getsockname.return_value': ['1.2.3.4', '']}