From 2632795d94acd2703a420350e28cf30a26321cf5 Mon Sep 17 00:00:00 2001
From: Manuel Franceschini <livewire@google.com>
Date: Thu, 24 Jun 2010 13:57:49 +0200
Subject: [PATCH] Add function to retrieve family of an ip address

Signed-off-by: Manuel Franceschini <livewire@google.com>
Reviewed-by: Guido Trotter <ultrotter@google.com>
---
 lib/utils.py                  | 18 ++++++++++++++++++
 test/ganeti.utils_unittest.py | 10 ++++++++++
 2 files changed, 28 insertions(+)

diff --git a/lib/utils.py b/lib/utils.py
index 2f6d04ea1..f29b903d6 100644
--- a/lib/utils.py
+++ b/lib/utils.py
@@ -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.
 
diff --git a/test/ganeti.utils_unittest.py b/test/ganeti.utils_unittest.py
index e0cdd0dd6..6d489b267 100755
--- a/test/ganeti.utils_unittest.py
+++ b/test/ganeti.utils_unittest.py
@@ -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()
-- 
GitLab