Linux – How to dynamically find the name and type of interfaces attached to a system

ethernetlinuxlinux-networkingnetworkingwifi

I have a use case where I need to dynamically configure some files which includes the name of the interfaces present in system say eth0 , wlan0 . However when I change the system sometimes its changed to eth1 or wlan1 . From Ubuntu 14.04 the Ethernet interfaces are named as p2p1 , p1p1 like this and wireless interfaces as wlan0 or wlan1.

So we can say the interfaces name can be anything, doesn't matter as long as we can find what names are given to what kind of interface .

I wrote a small script for that but I don't know if there could be a better way to find this which works across all the Linux based system .

#!/bin/bash

# check if directory exist 
DIRECTORY=/sys/class/net
wifi_interface=""
lan_interface=""
if [ -d "$DIRECTORY" ]; then
    cd $DIRECTORY

    ilist=`ifconfig -s  | awk '{print $1}' | tail -n +2`

    # array length
    ilist_len=`echo "${ilist[@]}" | wc -l`

    # empty array 
    il=

    # Iterating over interfaces 
    for i in $(seq 1 $ilist_len)
    do 
        iname=`echo $ilist | sed -n "$i"p`
        echo $iname
        if [ "$iname" != "lo" ]; then
            cur_dir=$DIRECTORY/$iname
            cd $cur_dir
            if [ -d "$cur_dir/wireless" ]; then
                wifi_interface=$iname
            else 
                lan_interface=$iname
            fi
        fi
        pwd
        cd ~
    done
    exit 0
else
    echo "Can't find the directories ! Something went wrong "
    exit 0
fi

In the above script I decided the interfaces type based on the presence or absence of directory /sys/class/net/<INTERFACE>/wireless. The script assumes that only 1-1 interface is present for Ethernet and wireless.

I doubt that the wireless directory is always present in all of the wireless interfaces . For example in case of virtual wireless interfaces.

Best Answer

Today, for a relatively modern Linux distro I would initially try to use the ip command

ip link show

and then filter it's output to get a list of interfaces.

You can also use ifconfig -a but newer releases of some distros are nolonger installing this by default.

Similarly netstat -i may be useful.

You can use the iwconfig command to determine if an interface is wireless or not

iwconfig ens160
ens160    no wireless extensions.
Related Topic