1 # vim:set ts=4 sw=4 expandtab:
2 # (c) Copyright 2008 The Trustees of Princeton University
11 SIOCGIFADDR_struct = "16xH2xI8x"
12 SIOCGIFHWADDR = 0x8927
13 SIOCGIFHWADDR_struct = "16x2x6B8x"
16 ip = socket.ntohl(nip)
17 return "%d.%d.%d.%d" % ((ip & 0xff000000) >> 24,
18 (ip & 0x00ff0000) >> 16,
19 (ip & 0x0000ff00) >> 8,
22 def gifaddr(interface):
25 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
26 ifreq = fcntl.ioctl(s.fileno(), SIOCGIFADDR, struct.pack("16s16x", interface))
27 (family, ip) = struct.unpack(SIOCGIFADDR_struct, ifreq)
28 if family == socket.AF_INET:
37 ip = subprocess.Popen(["/sbin/ip", "-4", "addr", "ls"],
38 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
39 stderr=subprocess.PIPE, close_fds=True)
40 (stdout, stderr) = ip.communicate()
41 # no wait is needed when using communicate
42 for line in stdout.split("\n"):
43 fields = [ field.strip() for field in line.split() ]
44 if fields and fields[0] == "inet":
45 # fields[-1] is the last column in fields, which has the interface name
46 # fields[1] has the IP address / netmask width
47 ret[fields[-1]] = fields[1].split("/")[0]
50 def gifhwaddr(interface):
53 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
54 ifreq = fcntl.ioctl(s.fileno(), SIOCGIFHWADDR, struct.pack("16s16x", interface))
55 mac = struct.unpack(SIOCGIFHWADDR_struct, ifreq)
56 return "%02x:%02x:%02x:%02x:%02x:%02x" % mac