February 4, 2010

Print Active Network Interface List in Linux using Python

I'm checking the replies of my previous code on Create network interfaces list using Python. E A Faisal suggestion to use /proc/net/dev is somehow seems interesting to me. Now, let's do some python code for fun before going out to lunch.

Here is my code to get the same result as my previous python code to list the network interfaces:


# read the file /proc/net/dev
f = open('/proc/net/dev','r')

# put the content to list
ifacelist = f.read().split('\n')

# close the file

# remove 2 lines header

# loop to check each line
for line in ifacelist:

ifacedata = line.replace(' ','').split(':')

# check the data have 2 elements
if len(ifacedata) == 2:

# check the interface is up (Transmit/Receive data)
if int(ifacedata[1]) > 0:

# print the interface
print ifacedata[0]

Seems like it is working on my ubuntu linux (in the office ). I believe it should possibly work on other linux without any issue with that SIOCGIFCONF and ioctl. And the code is even simpler.

That's all for now... I'm going out for lunch. Happy python coding!

Share This Article:

Bookmark This Article:
Feed Me Digg Technorati del.icio.us Best to Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy


jimchris said...

Nice work, now how do we get ip address from ifacedata?

Thx and Enjoy

ApOgEE said...

Hi jimchris,

I've made a new post to answer your question here:
Python Code to Get IP Address From Interface Name

sgtrock said...

Sorry for following up on such an old post, but I thought you might be interested in what I found on my system. I am currently running Debian Squeeze with Network Manager enabled. I have a static interface, eth0, defined through /etc/network/interfaces and a second, eth1, that is managed by Network Manager.

Most of the time eth1 is unplugged. It only gets used when I take my PC with me. That way, I have the luxury of using my PC as a local server with a static address at home, and can still easily plug into another network when I'm on the road.

When I ran the code in this post while I had eth0 in at home, my output looked like:


When I ran it using the code snippet from your earlier post, I got this:



Interesting, huh? Note that socket.socket was producing a blank line for both eth0 and eth1 while /proc/net/dev listed only the two active interfaces.

Any idea why /proc/net/dev would show eth0 but socket.socket would not?