Linux getting all network interface names

前端 未结 6 1949
傲寒
傲寒 2020-12-01 08:30

I need to collect all the interface names, even the ones that aren\'t up at the moment. Like ifconfig -a.

getifaddrs() is iterating through

6条回答
  •  忘掉有多难
    2020-12-01 09:05

    I need the main device that is being used by the system (assuming there is only one) such as eth0 wlan0 or whatever RHEL7 is trying to do...

    The best I hacked together was this:

    #!/bin/bash
    # -- Get me the interface for the main ip on system
    
    for each in $(ls -1 /sys/class/net) ;do 
    
        result=$(ip addr show $each | awk '$1 == "inet" {gsub(/\/.*$/, "", $2); print $2}' | grep "$(hostname -I | cut -d' ' -f1)")
    
        if [ ! -z "${result// }" ] && [ -d /sys/class/net/${each// } ] ;then
                echo "Device: $each IP: $result"
                break;
        fi
    
    done
    

    Sample output:

        ./maineth.sh  
        Device: enp0s25 IP: 192.168.1.6
    

提交回复
热议问题