Search code examples
linuxbashsedip

How to find network interface name


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.


Solution

  • Not sure if this helps, but it seems that ip route get will show which interface it uses to connect to a remote host.

    ubuntu@ip-10-40-24-21:/nail/srv/elasticsearch$ ip route get 8.8.8.8
    8.8.8.8 via <gateway address> dev eth0  src <eth0 IP Address>
    

    of course you could automate that in shell script with something like,

    ip route get 8.8.8.8 | awk '{ print $NF; exit }'