How can I retrieve from the command line (or a shell script) only the name of the active network interface, in Linux? If there are several active interfaces, I want just one (selected arbitrarily).
2 Answers
The modern way of doing this is using the ip
command. For example, on my system with my wireless connection active, I get:
$ ip addr show 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: eno1: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc fq_codel state DOWN group default qlen 1000 link/ether 00:26:b9:dd:2c:28 brd ff:ff:ff:ff:ff:ff 3: wlp3s0b1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000 link/ether c4:46:19:5f:dc:f5 brd ff:ff:ff:ff:ff:ff inet 192.168.1.4/24 brd 192.168.1.255 scope global wlp3s0b1 ← valid_lft forever preferred_lft forever inet6 fe80::c646:19ff:fe5f:dcf5/64 scope link valid_lft forever preferred_lft forever 16: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default qlen 100 link/none inet 123.167.217.2/24 brd 123.167.217.255 scope global tun0 ← valid_lft forever preferred_lft forever
The active interface(s) have both an inet
entry and a broadcast (brd
) address.
You can show all such interfaces with:
$ ip addr show | awk '/inet.*brd/{print $NF}'
wlp3s0b1
tun0
If you want only one, you can get the first one (only) with:
$ ip addr show | awk '/inet.*brd/{print $NF; exit}'
wlp3s0b1
The exit
statement tells awk
to stop searching
after it finds the first match.
-
2
-
-
@aurelien no worries. I just mentioned it because you're new and might not know how the site works. Feel free to not accept and wait for another answer too, if you prefer.– terdon ♦Mar 15, 2016 at 18:22
-
Your command just do exactly what I have request for ... So I can just says thanks and accept it :-)– aurelienMar 15, 2016 at 18:24
-
not every "active" interface has a broadcast address - e.g. ppp interfaces don't.– casMar 15, 2016 at 22:49
ifconfig | sed 's/[ \t].*//;/^\(lo\|\)$/d'
-
1The problem with that approach is that
ifconfig
is being replaced byip
.– terdon ♦Mar 15, 2016 at 18:18 -
ip a | sed 's/[ \t].*//;/^\(lo\|\)$/d'
respond an empty thing .. but +1 for this nice try :-) @Maslov-Anton– aurelienOct 24, 2018 at 12:39
ifconfig
is getting deprecated in favor ofip
and its ilk.