1
2
3
4
5
6
7
8
9
10
11 import array
12 import fcntl
13 import struct
14 import socket
15
16
18 """ ioctl stuff """
19
20 IFNAMSIZ = 16
21
22
23
24 SIOCGIFADDR = 0x8915
25 SIOCGIFBRDADDR = 0x8919
26 SIOCGIFCONF = 0x8912
27 SIOCGIFFLAGS = 0x8913
28 SIOCGIFMTU = 0x8921
29 SIOCGIFNETMASK = 0x891b
30 SIOCSIFADDR = 0x8916
31 SIOCSIFBRDADDR = 0x891a
32 SIOCSIFFLAGS = 0x8914
33 SIOCSIFMTU = 0x8922
34 SIOCSIFNETMASK = 0x891c
35
36
37
38 IFF_UP = 0x1
39 IFF_BROADCAST = 0x2
40 IFF_DEBUG = 0x4
41 IFF_LOOPBACK = 0x8
42 IFF_POINTOPOINT = 0x10
43 IFF_NOTRAILERS = 0x20
44 IFF_RUNNING = 0x40
45 IFF_NOARP = 0x80
46 IFF_PROMISC = 0x100
47 IFF_ALLMULTI = 0x200
48 IFF_MASTER = 0x400
49 IFF_SLAVE = 0x800
50 IFF_MULTICAST = 0x1000
51 IFF_PORTSEL = 0x2000
52 IFF_AUTOMEDIA = 0x4000
53
54
56
57 self.sockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
58
60 return fcntl.ioctl(self.sockfd.fileno(), func, args)
61
62 - def _call(self, ifname, func, ip = None):
63
64 if ip is None:
65 data = (ifname + '\0'*32)[:32]
66 else:
67 ifreq = (ifname + '\0' * self.IFNAMSIZ)[:self.IFNAMSIZ]
68 data = struct.pack("16si4s10x", ifreq, socket.AF_INET, socket.inet_aton(ip))
69
70 try:
71 result = self._ioctl(func, data)
72 except IOError:
73 return None
74
75 return result
76
78 """ Get all interface names in a list """
79
80 buffer = array.array('c', '\0' * 1024)
81 ifconf = struct.pack("iP", buffer.buffer_info()[1], buffer.buffer_info()[0])
82 result = self._ioctl(self.SIOCGIFCONF, ifconf)
83
84
85 iflist = []
86 size, ptr = struct.unpack("iP", result)
87 for idx in range(0, size, 32):
88 ifconf = buffer.tostring()[idx:idx+32]
89 name, dummy = struct.unpack("16s16s", ifconf)
90 name, dummy = name.split('\0', 1)
91 iflist.append(name)
92
93 return iflist
94
96 """ Get the inet addr for an interface """
97 result = self._call(ifname, self.SIOCGIFADDR)
98 return socket.inet_ntoa(result[20:24])
99
101 """ Get the netmask for an interface """
102 result = self._call(ifname, self.SIOCGIFNETMASK)
103 return socket.inet_ntoa(result[20:24])
104
106 """ Get the broadcast addr for an interface """
107 result = self._call(ifname, self.SIOCGIFBRDADDR)
108 return socket.inet_ntoa(result[20:24])
109
111 """ Check whether interface is UP """
112 result = self._call(ifname, self.SIOCGIFFLAGS)
113 flags, = struct.unpack('H', result[16:18])
114 return (flags & self.IFF_UP) != 0
115
117 """ Get the MTU size of an interface """
118 data = self._call(ifname, self.SIOCGIFMTU)
119 mtu = struct.unpack("16si12x", data)[1]
120 return mtu
121