1bb009561c18ed457d0334b1d480ba5307f4affb
[pyplnet.git] / sioc.py
1 # $Id$
2 # vim:set ts=4 sw=4 expandtab:
3 # (c) Copyright 2008 The Trustees of Princeton University
4
5 import os
6 import socket
7 import fcntl
8 import struct
9
10 SIOCGIFADDR = 0x8915
11 SIOCGIFADDR_struct = "16xH2xI8x"
12 SIOCGIFHWADDR = 0x8927
13 SIOCGIFHWADDR_struct = "16x2x6B8x"
14
15 def _format_ip(nip):
16     ip = socket.ntohl(nip)
17     return "%d.%d.%d.%d" % ((ip & 0xff000000) >> 24,
18                             (ip & 0x00ff0000) >> 16,
19                             (ip & 0x0000ff00) >> 8,
20                             (ip & 0x000000ff))
21
22 def gifaddr(interface):
23     s = None
24     try:
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:
29             return _format_ip(ip)
30     finally:
31         if s is not None:
32             s.close()
33     return None
34
35 def gifconf():
36     interfaces = os.listdir("/sys/class/net")
37     s = None
38     ret = {}
39     try:
40         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
41         for interface in interfaces:
42             try:
43                 ifreq = fcntl.ioctl(s.fileno(), SIOCGIFADDR,
44                                     struct.pack("16sH14x", interface, socket.AF_INET))
45                 (family, ip) = struct.unpack(SIOCGIFADDR_struct, ifreq)
46                 if family == socket.AF_INET:
47                     ret[interface] = _format_ip(ip)
48                 else:
49                     raise Exception
50             except:
51                 ret[interface] = "0.0.0.0"
52     finally:
53         if s is not None:
54             s.close()
55     return ret
56
57 def gifhwaddr(interface):
58     s = None
59     try:
60         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
61         ifreq = fcntl.ioctl(s.fileno(), SIOCGIFHWADDR, struct.pack("16s16x", interface))
62         mac = struct.unpack(SIOCGIFHWADDR_struct, ifreq)
63         return "%02x:%02x:%02x:%02x:%02x:%02x" % mac
64     finally:
65         s.close()
66     return None