I am looking for a command line solution that would return me the primary (first) IP address of the localhost, other than 127.0.0.1
The solution should work at least for Linux (Debian and RedHat) and OS X 10.7+
I am aware that ifconfig is available on both but its output is not so consistent between these platforms.
Use
grepto filter IP address fromifconfig:ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'Or with
sed:ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'If you are only interested in certain interfaces, wlan0, eth0, etc. then:
ifconfig wlan0 | ...You can alias the command in your
.bashrcto create your own command calledmyipfor instance.alias myip="ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'"A much simpler way is
hostname -I(hostname -ifor older versions ofhostnamebut see comments). However, this is on Linux only.