Parse ifconfig to get only my IP address using Bash
Both the following work here (CentOS 5).
ip addr show eth0 | awk '$1 == "inet" {gsub(/\/.*$/, "", $2); print $2}'
ifconfig eth0 | awk '/inet addr/ {gsub("addr:", "", $2); print $2}'
For OS X (v10.11 (El Capitan) at least):
ifconfig en0 | awk '$1 == "inet" {print $2}'
This is the more "agnostic" way to get the IP address, regardless of you *nix system (Mac OS, Linux), interface name, and even your locale configuration:
ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d:
If you have more than one active IP, will listed each one in a separated line. If you want just the first IP, add | head -n1
to the expression:
ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" \
| grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | head -n1
And if you want the IP address of a specific interface, replace the first expression ifconfig
by ifconfig INTERFACENAME
, for example ifconfig eth0 | grep -E ...
.
Finally, you noticed that one of the things the script does is to omit the IP 127.0.0.1
called by sysadmins and developers "localhost", but take into account that some applications may also add virtual network devices with an IP that may be the one returned if is not added to the omit list, eg. Docker adds a virtual interface docker0
that usually has the IP 172.17.0.1
, if you want to omit this IP along with the "localhost" one, change the expression grep -v 127.0.0.1
to take into account the another IP. In this case (omit localhost and docker) the final expression will be:
ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v '[127.0|172.17].0.1' | awk '{ print $2 }' | cut -f2 -d: | head -n1
These are some examples mentioned in this page that fails in some circumstances and why:
ip route ...
: theip
command isn't installed in OSX machines.hostname -I
: the-I
option is invalid in OSX.ifconfig en0 ...
: the interfaces names (eth0
,en0
) are different in Linux and OSX, and in Linux the name depends also of the interface type (ethX for ethernet connection, wlanX for wireless, etc.).python -c 'import socket; print(socket.gethostbyname(socket.gethostname()))'
: this got me127.0.1.1
(a loopback IP) in Ubuntu Linux 14.04, so doesn't work.ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | head -n1 | cut -f2 -d: | cut -f1 -d ' '
: the Geograph's post is the more close, but doesn't work in some Linux distributions withoutLANG=en
configured, because the textinet addr:
thatgrep
looks for is output with a different text in other locales, and in Mac OS that label is also different.
In case of eth0, the following works for me. Try to tweak it with the same logic.
ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'