Tagging module pyplnet - pyplnet-4.3-1
[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     try:
37         interfaces = os.listdir("/sys/class/net")
38     except:
39         interfaces = []
40     s = None
41     ret = {}
42     try:
43         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
44         for interface in interfaces:
45             try:
46                 ifreq = fcntl.ioctl(s.fileno(), SIOCGIFADDR,
47                                     struct.pack("16sH14x", interface, socket.AF_INET))
48                 (family, ip) = struct.unpack(SIOCGIFADDR_struct, ifreq)
49                 if family == socket.AF_INET:
50                     ret[interface] = _format_ip(ip)
51                 else:
52                     raise Exception
53             except:
54                 ret[interface] = "0.0.0.0"
55     finally:
56         if s is not None:
57             s.close()
58     return ret
59
60 def gifhwaddr(interface):
61     s = None
62     try:
63         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
64         ifreq = fcntl.ioctl(s.fileno(), SIOCGIFHWADDR, struct.pack("16s16x", interface))
65         mac = struct.unpack(SIOCGIFHWADDR_struct, ifreq)
66         return "%02x:%02x:%02x:%02x:%02x:%02x" % mac
67     finally:
68         s.close()
69     return None