Friday, February 19, 2010

Howto get a list of network interfaces in Linux, part 1

Hi folks,

Today we are going to become a little bit more technical. Some of you might wonder how to get a list of the network interfaces. For our first part, we are going to consider the shell script case.

Little disclaimer first, I am not an expert at shell-scripts at all, my abilities are limited to understanding the random scripts I encounter during my daily use of Linux on my computers, and writing the occasional script that saves some time when having to automate some boring tasks (converting a few gigs of  videos is boring).

So, where shall we begin ? This is all quite easy : the kernel has a list of devices that is updated whenever a new device is added (through hotplugging, module loading, virtual device creation, and so on) or removed. As for many important kernel hosted pieces of information, this list can be accessed through the /proc filesystem. If you are curious and want to know more about all this, you can check net/core/dev.c from your current kernel, it should be there. Look for dev_base_head and dev_seq_printf_stats.

Let's have a look at that proc entry :
Inter-|   Receive                                                |  Transmit face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed    lo:    1384      20    0    0    0     0          0         0     1384      20    0    0    0     0       0          0  eth1:14664583   22189    0    0    0     0          0       660  3069813   15105    0    0    0     0       0          0 wlan1:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0  pan0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0

Great, It's all there in a neat and easy to parse format. Let's trash the first line, keep only the leftmost part of all the other ones, and trim the leading whitespace.

As I told you earlier, I am not claiming to be a shell-script expert, but that script does work ! Here it is, using bash.
#!/bin/bashfor i in `cat /proc/net/dev | grep ':' | cut -d ':' -f 1`do  ifname=`echo $i | tr -d ' '`  echo "Interface : $i"done

And of course, we get the expected results, at least on my debian box.

Results for a random debian GNU/Linux box :
bash$ ./ Interface : loInterface : eth1Interface : wlan1Interface : pan

That code snippet is given to you for free, just leave a comment if you love or hate it. Next time we will look at a little longer piece of C code to obtain the same kind of information, without resorting to opening the /proc file, of course.

1 comment:

Zirion said...

Just what I was looking for.