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

ifconfigipnetworkingscripting

I need to create a script that outputs the internal IP address, that is configured as the default Interface.

Best Answer

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
Related Question