Create network interfaces list using Python

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
Message-ID: <52d26d931002030748pd2c6321p1290b1eeee703...@mail.gmail.com>
Subject: showing interfaces
From: Umarzuki Mochlis <umarz...@gmail.com>
To: pythonmy@googlegroups.com

Hi all,

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

--
Regards,

Umarzuki Mochlis

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.
You can read the discussion thread on python.my mailing list: showing interfaces

Answer:
Here is how you can create network interfaces list with python:

import array
import struct
import socket
import fcntl

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
def get_iface_list():
# 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()[0])))[0]

# convert it to string
namestr = names.tostring()

# return the interfaces as array
return [namestr[i:i+32].split('\0', 1)[0] 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:
print iface

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!


Comments

Popular posts from this blog

How to Create Hyperlink on Blogger Post

How to Add a Sudo User on AlmaLinux 9.2 (Turquoise Kodkod): A Step-by-Step Guide

How to Show and Hide Text in Blog Post