Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find network interface name

Tags:

linux

bash

sed

ip

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.

like image 417
artfulrobot Avatar asked Sep 18 '12 09:09

artfulrobot


2 Answers

The main NIC will usually have a default route. So:

ip -o -4 route show to default

The NIC:

ip -o -4 route show to default | awk '{print $5}'

The gateway:

ip -o -4 route show to default | awk '{print $3}'

Unlike ifconfig, ip has a consistent & parsable output. It only works on Linux; it won't work on other Unixen.

like image 134
user150471 Avatar answered Oct 02 '22 22:10

user150471


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 }'
like image 42
gatoatigrado Avatar answered Oct 02 '22 23:10

gatoatigrado