Setting tag pyplnet-7.0-0
[pyplnet.git] / sioc.py
diff --git a/sioc.py b/sioc.py
index fd657ef..1213dd6 100644 (file)
--- a/sioc.py
+++ b/sioc.py
@@ -1,4 +1,3 @@
-# $Id$
 # vim:set ts=4 sw=4 expandtab:
 # (c) Copyright 2008 The Trustees of Princeton University
 
@@ -6,6 +5,7 @@ import os
 import socket
 import fcntl
 import struct
+import subprocess
 
 SIOCGIFADDR = 0x8915
 SIOCGIFADDR_struct = "16xH2xI8x"
@@ -20,6 +20,9 @@ def _format_ip(nip):
                             (ip & 0x000000ff))
 
 def gifaddr(interface):
+    # for python3
+    if isinstance(interface, str):
+        interface = interface.encode()
     s = None
     try:
         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
@@ -33,31 +36,25 @@ def gifaddr(interface):
     return None
 
 def gifconf():
-    try:
-        interfaces = os.listdir("/sys/class/net")
-    except:
-        interfaces = []
-    s = None
     ret = {}
-    try:
-        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
-        for interface in interfaces:
-            try:
-                ifreq = fcntl.ioctl(s.fileno(), SIOCGIFADDR,
-                                    struct.pack("16sH14x", interface, socket.AF_INET))
-                (family, ip) = struct.unpack(SIOCGIFADDR_struct, ifreq)
-                if family == socket.AF_INET:
-                    ret[interface] = _format_ip(ip)
-                else:
-                    raise Exception
-            except:
-                ret[interface] = "0.0.0.0"
-    finally:
-        if s is not None:
-            s.close()
+    ip = subprocess.Popen(["/sbin/ip", "-4", "addr", "show"],
+                          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                          stderr=subprocess.PIPE, close_fds=True,
+                          universal_newlines=True)
+    (stdout, stderr) = ip.communicate()
+    # no wait is needed when using communicate
+    for line in stdout.split("\n"):
+        fields = [ field.strip() for field in line.split() ]
+        if fields and fields[0] == "inet":
+            # fields[-1] is the last column in fields, which has the interface name
+            # fields[1] has the IP address / netmask width
+            ret[fields[-1]] = fields[1].split("/")[0]
     return ret
 
 def gifhwaddr(interface):
+    # for python3
+    if isinstance(interface, str):
+        interface = interface.encode()
     s = None
     try:
         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)