How to get the primary IP address of the local machine on Linux and OS X?


I am looking for a command line solution that would return me the primary (first) IP address of the localhost, other than

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.

This question is tagged with bash unix ip ifconfig

~ Asked on 2012-11-10 13:32:11

The Best Answer is


Use grep to filter IP address from ifconfig:

ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v ''

Or with sed:

ifconfig | sed -En 's/;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 .bashrc to create your own command called myip for instance.

alias myip="ifconfig | sed -En 's/;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'"

A much simpler way is hostname -I (hostname -i for older versions of hostname but see comments). However, this is on Linux only.

~ Answered on 2012-11-10 13:39:13


The following will work on Linux but not OSX.

This doesn't rely on DNS at all, and it works even if /etc/hosts is not set correctly (1 is shorthand for

ip route get 1 | awk '{print $NF;exit}'

or avoiding awk and using Google's public DNS at for obviousness:

ip route get | head -1 | cut -d' ' -f8

A less reliable way: (see comment below)

hostname -I | cut -d' ' -f1

~ Answered on 2014-09-15 15:08:03

Most Viewed Questions: