Commit 05edafd3 authored by Santi Raffa's avatar Santi Raffa Committed by Thomas Thrainer

netutils: Add ValidatePortNumber method

This method accepts a port number and checks that it is in fact valid.
Signed-off-by: default avatarSanti Raffa <rsanti@google.com>
Signed-off-by: default avatarThomas Thrainer <thomasth@google.com>
Reviewed-by: default avatarThomas Thrainer <thomasth@google.com>
parent 267520ba
......@@ -267,6 +267,31 @@ class Hostname:
return hostname
def ValidatePortNumber(port):
"""Returns the validated integer port number if it is valid.
@param port: the port number to be validated
@raise ValueError: if the port is not valid
@rtype: int
@return: the validated value.
"""
try:
port = int(port)
except TypeError:
raise errors.ProgrammerError("ValidatePortNumber called with non-numeric"
" type %s." % port.__class__.__name__)
except ValueError:
raise ValueError("Invalid port value: '%s'" % port)
if not 0 < port < 2 ** 16:
raise ValueError("Invalid port value: '%d'" % port)
return port
def TcpPing(target, port, timeout=10, live_port_needed=False, source=None):
"""Simple ping implementation using TCP connect(2).
......
......@@ -531,5 +531,18 @@ class TestIpParsing(testutils.GanetiTestCase):
addr[4][0] == "192.0.2.1")
class TestValidatePortNumber(unittest.TestCase):
"""Test netutils.ValidatePortNumber"""
def testPortNumberInt(self):
self.assertRaises(ValueError, lambda: \
netutils.ValidatePortNumber(500000))
self.assertEqual(netutils.ValidatePortNumber(5000), 5000)
def testPortNumberStr(self):
self.assertRaises(ValueError, lambda: \
netutils.ValidatePortNumber("pinky bunny"))
self.assertEqual(netutils.ValidatePortNumber("5000"), 5000)
if __name__ == "__main__":
testutils.GanetiTestProgram()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment