How to display the IP address of the default Interface with Internet connection?

Lots of good answers here, but wanted to throw in my usual approach:

The simplest solution is to get the route for a public internet address:

$ ip route get 1.1.1.1 | grep -oP 'src \K\S+'
192.168.0.20

Another solution is to get the default gateway, and then get the IP addr used to communicate with that gateway:

$ ip route get $(ip route show 0.0.0.0/0 | grep -oP 'via \K\S+') | grep -oP 'src \K\S+'
192.168.0.20

Here's another slightly terser method using procfs (assumes you're using Linux):

default_iface=$(awk '$2 == 00000000 { print $1 }' /proc/net/route)
ip addr show dev "$default_iface" | awk '$1 ~ /^inet/ { sub("/.*", "", $2); print $2 }'

This returns both the IPv4 and (if available) the IPv6 address of the interface. You can change the test if you only want one or the other (look for inet for IPv4, and inet6 for IPv6).


$ default_iface=$(awk '$2 == 00000000 { print $1 }' /proc/net/route)
$ ip addr show dev "$default_iface" | awk '$1 ~ /^inet/ { sub("/.*", "", $2); print $2 }'
10.0.2.15
fe80::a00:27ff:fe45:b085
$ ip addr show dev "$default_iface" | awk '$1 == "inet" { sub("/.*", "", $2); print $2 }'
10.0.2.15
$ ip addr show dev "$default_iface" | awk '$1 == "inet6" { sub("/.*", "", $2); print $2 }'
fe80::a00:27ff:fe45:b085