While checking my email this morning, I found a python question on python.my mailing list which sound like this:
Date: Wed, 3 Feb 2010 23:48:10 +0800
Subject: showing interfaces
From: Umarzuki Mochlis <umarz...@gmail.com>
I wonder how I can output network interfaces with python the same
way I can with these commands on linux
sudo ifconfig | cut -d " " -f 1 > ifconfig.txt
sed '/ *#/d; /^ *$/d' < ifconfig.txt
For those who couldn't imagine the output of those two lines command in the question, here is the explanation:
- The first command write to 'ifconfig.txt' the name of up interfaces which comes from ifconfig output and remove other unwanted informations.
- the second line read the 'ifconfig.txt' file, remove empty lines and print the list on the screen.
Here is how you can create network interfaces list with python:
SIOCGIFCONF = 0x8912 #define SIOCGIFCONF
BYTES = 4096 # Simply define the byte size
# get_iface_list function definition
# this function will return array of all 'up' interfaces
# create the socket object to get the interface list
sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# prepare the struct variable
names = array.array('B', '\0' * BYTES)
# the trick is to get the list from ioctl
bytelen = struct.unpack('iL', fcntl.ioctl(sck.fileno(), SIOCGIFCONF, struct.pack('iL', BYTES, names.buffer_info())))
# convert it to string
namestr = names.tostring()
# return the interfaces as array
return [namestr[i:i+32].split('\0', 1) for i in range(0, bytelen, 32)]
# now, use the function to get the 'up' interfaces array
ifaces = get_iface_list()
# well, what to do? print it out maybe...
for iface in ifaces:
This code is tested to be working in my ubuntu linux. Since I made SIOCGIFCONF ioctl number (0x8912) hardcoded, it may seems broken on other UNIX like system. However, you may modified the code to be compatible with your system when you understand it. I hope this snippet can help others too. Enjoy coding!