2
Network introspection utilities using ioctl and the /proc filesystem.
9
__all__ = ["get_active_device_info", "get_network_traffic"]
11
# from header /usr/include/bits/ioctls.h
14
SIOCGIFNETMASK = 0x891b
15
SIOCGIFBRDADDR = 0x8919
17
SIOCGIFHWADDR = 0x8927
20
# struct definition from header /usr/include/net/if.h
21
# the struct size varies according to the platform arch size
22
# a minimal c program was used to determine the size of the
23
# struct, standard headers removed for brevity.
27
printf("Size of struct %lu\n", sizeof(struct ifreq));
31
IF_STRUCT_SIZE_32 = 32
32
IF_STRUCT_SIZE_64 = 40
36
"""Returns C{True} if the platform is 64-bit, otherwise C{False}."""
37
return struct.calcsize("l") == 8
40
# initialize the struct size as per the machine's archictecture
41
IF_STRUCT_SIZE = is_64() and IF_STRUCT_SIZE_64 or IF_STRUCT_SIZE_32
44
def get_active_interfaces(sock):
45
"""Generator yields active network interface names.
47
@param sock: a socket instance.
51
# Setup an an array to hold our response, and initialized to null strings.
52
interfaces = array.array("B", "\0" * max_interfaces * IF_STRUCT_SIZE)
53
buffer_size = interfaces.buffer_info()[0]
54
packed_bytes = struct.pack(
55
"iL", max_interfaces * IF_STRUCT_SIZE, buffer_size)
57
byte_length = struct.unpack(
58
"iL", fcntl.ioctl(sock.fileno(), SIOCGIFCONF, packed_bytes))[0]
60
result = interfaces.tostring()
62
# Generator over the interface names
64
for index in range(0, byte_length, IF_STRUCT_SIZE):
65
ifreq_struct = result[index:index+IF_STRUCT_SIZE]
66
interface_name = ifreq_struct[:ifreq_struct.index("\0")]
67
if interface_name not in already_found:
68
already_found.add(interface_name)
72
def get_broadcast_address(sock, interface):
73
"""Return the broadcast address associated to an interface.
75
@param sock: a socket instance.
76
@param interface: The name of the interface.
78
return socket.inet_ntoa(fcntl.ioctl(
81
struct.pack("256s", interface[:15]))[20:24])
84
def get_netmask(sock, interface):
85
"""Return the network mask associated to an interface.
87
@param sock: a socket instance.
88
@param interface: The name of the interface.
90
return socket.inet_ntoa(fcntl.ioctl(
93
struct.pack("256s", interface[:15]))[20:24])
96
def get_ip_address(sock, interface):
97
"""Return the IP address associated to the interface.
99
@param sock: a socket instance.
100
@param interface: The name of the interface.
102
return socket.inet_ntoa(fcntl.ioctl(
105
struct.pack("256s", interface[:15]))[20:24])
108
def get_mac_address(sock, interface):
110
Return the hardware MAC address for an interface in human friendly form,
111
ie. six colon separated groups of two hexadecimal digits.
113
@param sock: a socket instance.
114
@param interface: The name of the interface.
116
mac_address = fcntl.ioctl(
117
sock.fileno(), SIOCGIFHWADDR, struct.pack("256s", interface[:15]))
118
return "".join(["%02x:" % ord(char) for char in mac_address[18:24]])[:-1]
121
def get_flags(sock, interface):
122
"""Return the integer value of the interface flags for the given interface.
124
@param sock: a socket instance.
125
@param interface: The name of the interface.
126
@see /usr/include/linux/if.h for the meaning of the flags.
129
sock.fileno(), SIOCGIFFLAGS, struct.pack("256s", interface[:15]))
130
return struct.unpack("H", data[16:18])[0]
133
def get_active_device_info():
135
Returns a dictionary containing information on each active network
136
interface present on a machine.
139
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_IP)
140
for interface in get_active_interfaces(sock):
141
interface_info = {"interface": interface}
142
interface_info["ip_address"] = get_ip_address(sock, interface)
143
interface_info["mac_address"] = get_mac_address(sock, interface)
144
interface_info["broadcast_address"] = get_broadcast_address(sock,
146
interface_info["netmask"] = get_netmask(sock, interface)
147
interface_info["flags"] = get_flags(sock, interface)
148
results.append(interface_info)
153
def get_network_traffic(source_file="/proc/net/dev"):
155
Retrieves an array of information regarding the network activity per
158
netdev = open(source_file, "r")
159
lines = netdev.readlines()
162
# Parse out the column headers as keys.
163
_, receive_columns, transmit_columns = lines[1].split("|")
164
columns = ["recv_%s" % column for column in receive_columns.split()]
165
columns.extend(["send_%s" % column for column in transmit_columns.split()])
167
# Parse out the network devices.
169
for line in lines[2:]:
172
device, data = line.split(":")
173
device = device.strip()
174
devices[device] = dict(zip(columns, map(long, data.split())))
178
if __name__ == "__main__":
180
pprint.pprint(get_active_device_info())