Commit 2632795d authored by Manuel Franceschini's avatar Manuel Franceschini
Browse files

Add function to retrieve family of an ip address


Signed-off-by: default avatarManuel Franceschini <livewire@google.com>
Reviewed-by: default avatarGuido Trotter <ultrotter@google.com>
parent c0c3fa27
......@@ -1352,6 +1352,24 @@ def IsValidIP(ip):
return IsValidIP4(ip) or IsValidIP6(ip)
def GetAddressFamily(ip):
"""Get the address family of the given address.
@type ip: str
@param ip: ip address whose family will be returned
@rtype: int
@return: socket.AF_INET or socket.AF_INET6
@raise errors.GenericError: for invalid addresses
"""
if IsValidIP6(ip):
return socket.AF_INET6
elif IsValidIP4(ip):
return socket.AF_INET
else:
raise errors.GenericError("Address %s not valid" % ip)
def IsValidShellParam(word):
"""Verifies is the given word is safe from the shell's p.o.v.
......
......@@ -2464,5 +2464,15 @@ class TestIsValidIP(unittest.TestCase):
self.assertFalse(utils.IsValidIP("a:g::1"))
class TestGetAddressFamily(unittest.TestCase):
def test(self):
self.assertEqual(utils.GetAddressFamily("127.0.0.1"), socket.AF_INET)
self.assertEqual(utils.GetAddressFamily("10.2.0.127"), socket.AF_INET)
self.assertEqual(utils.GetAddressFamily("::1"), socket.AF_INET6)
self.assertEqual(utils.GetAddressFamily("fe80::a00:27ff:fe08:5048"),
socket.AF_INET6)
self.assertRaises(errors.GenericError, utils.GetAddressFamily, "0")
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