Linux – How to get only the name of the physical ethernet interface

linuxnetwork-interfacenetworking

Is there a way to get only the name of physical ethernet interface(i.e not virtual ethernet interface)?
To give a bit of background, I'm trying to get a few SBCs(RPi 3) to write their IP addresses to a DataBase. But since the names of the physical ethernet interface on different SBCs is not usually same, I'm finding it hard to get their IP addresses.

One way I could think of solving this is to give all the SBCs ethernet interface a common name like eth0. But this method feels a bit clunky. So, is there any other alternative to get only the name of physical ethernet interface?

Best Answer

You can tell which interfaces are virtual via

ls -l /sys/class/net/

which gives you this output:

[root@centos7 ~]# ls -l /sys/class/net/
total 0
lrwxrwxrwx. 1 root root 0 Mar 20 08:58 ens33 -> ../../devices/pci0000:00/0000:00:11.0/0000:02:01.0/net/ens33
lrwxrwxrwx. 1 root root 0 Mar 20 08:58 lo -> ../../devices/virtual/net/lo
lrwxrwxrwx. 1 root root 0 Mar 20 08:58 virbr0 -> ../../devices/virtual/net/virbr0
lrwxrwxrwx. 1 root root 0 Mar 20 08:58 virbr0-nic -> ../../devices/virtual/net/virbr0-nic

From there, you could grep to filter only non-virtual interfaces:

ls -l /sys/class/net/ | grep -v virtual

Another option is to use this small script, adapted from this answer, which prints the name of all interfaces which do not have a MAC address of 00:00:00:00:00:00 i.e. physical:

#!/bin/bash

for i in $(ip -o link show | awk -F': ' '{print $2}')
do
    mac=$(ethtool -P $i)
    [[ $mac != *"00:00:00:00:00:00"* ]] && echo "$i"
done
Related Question