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 ...
: the ip
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 me 127.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 without LANG=en
configured, because the text inet addr:
that grep
looks for is output with a different text in other locales, and in Mac OS that label is also different.
ifconfig en1 | sed -n '/inet addr/s/.*addr.\([^ ]*\) .*/\1/p'
Works on ubuntu, fedora at least... Based on yourifconfig en1
output, you can tweak more if required. – Tanhya/sbin/ifconfig $1 | grep "inet addr" | awk -F: '{print $2}' | awk '{print $1}'
. Defined the location as it isnt normally in usersPATH
except for root – Tabbitha