Alex Rivera | Logout

How to find network interface name

Asked 2012-09-18T09:31:04.990
19

I have a bash script that runs on a variety of different Ubuntu Linux machines. Its job is to find out the LAN IPv4 address of the localhost.

The script is using

ip addr show eth0 | sed -n '/inet /{s/^.*inet \([0-9.]\+\).*$/\1/;p}'

which is fine, but some machines for some reason use eth1 instead of eth0. I would like to be able to discover the LAN iface name, so I can substitute it in here instead of eth0.

Of course, if you can come up with a different oneliner that does the same thing, all good.

Edit
Report

1 Answer

3

How about searching for the string inet and brd (for broadcast)? That would give you:

ip addr show|egrep '^ *inet'|grep brd|awk -- '{ print $2; }'|sed -e 's:/[0-9]*$::'

Note that I'm using more commands than necessary; you can probably achieve the same thing with sed and a more complex regexp but I prefer a command that makes it obvious by which steps I arrive at the result.

If you want to run it in a single command, I suggest to try awk:

ip addr show|awk -- '$1 == "inet" && $3 == "brd"  { split($2,a,"/"); print a[1]; }'

which isn't much longer than the sed version but more readable.

+1 Slightly more readable:

ip addr show | awk '$1 == "inet" && $3 == "brd" { sub (/\/.*/,""); print $2 }'
answered 2012-09-18T09:58:08.933

Your Answer