Also added the VALID_IP_VERSIONS support constant.

Signed-off-by: Andrea Spadaccini <[email protected]>
---
 lib/constants.py |    1 +
 lib/netutils.py  |   48 ++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 49 insertions(+), 0 deletions(-)

diff --git a/lib/constants.py b/lib/constants.py
index 461b8f5..f0d88d2 100644
--- a/lib/constants.py
+++ b/lib/constants.py
@@ -551,6 +551,7 @@ IP6_ADDRESS_LOCALHOST = "::1"
 IP6_ADDRESS_ANY = "::"
 IP4_VERSION = 4
 IP6_VERSION = 6
+VALID_IP_VERSIONS = frozenset([IP4_VERSION, IP6_VERSION])
 TCP_PING_TIMEOUT = 10
 GANETI_RUNAS = "root"
 DEFAULT_VG = "xenvg"
diff --git a/lib/netutils.py b/lib/netutils.py
index 8b51e46..0baf9ad 100644
--- a/lib/netutils.py
+++ b/lib/netutils.py
@@ -28,6 +28,7 @@ the command line scripts.
 
 
 import errno
+import os
 import re
 import socket
 import struct
@@ -35,6 +36,7 @@ import IN
 
 from ganeti import constants
 from ganeti import errors
+from ganeti import utils
 
 # Structure definition for getsockopt(SOL_SOCKET, SO_PEERCRED, ...):
 # struct ucred { pid_t pid; uid_t uid; gid_t gid; };
@@ -62,6 +64,52 @@ def GetSocketCredentials(sock):
   return struct.unpack(_STRUCT_UCRED, peercred)
 
 
+def IsValidInterface(ifname):
+  """Validate an interface name.
+
+  @type ifname: string
+  @param ifname: Name of the network interface
+  @return: boolean indicating whether the interface name is valid or not.
+
+  """
+  return os.path.exists("/sys/class/net/%s" % ifname)
+
+
+def GetInterfaceIpAddresses(ifname, ip_version = constants.IP4_VERSION):
+  """Returns the IP addresses associated to the interface.
+
+  @type ifname: string
+  @param ifname: Name of the network interface
+  @type ip_version: int
+  @param ip_version: IP version of the addresses to return. Default is
+                     constants.IP4_VERSION.
+                     Can be constants.IP4_VERSION or constants.IP6_VERSION,
+                     other versions will silently return None.
+  @return: A list of strings containing the IP address, or None in case of 
errors.
+
+  """
+  if ip_version not in constants.VALID_IP_VERSIONS:
+    return None
+
+  result = utils.RunCmd("%s -%d addr show %s" % (
+    constants.IP_COMMAND_PATH,
+    ip_version,
+    ifname
+    ))
+
+  if result.failed:
+    return None
+
+  output_rows = result.output.split("\n")
+  addresses = []
+  for row in output_rows:
+    if "inet" in row:
+      address = row.split()[1]  # will contain IP/blocksize
+      addresses.append(address.split("/")[0])
+
+  return addresses
+
+
 def GetHostname(name=None, family=None):
   """Returns a Hostname object.
 
-- 
1.7.3.1

Reply via email to