How to get the primary IP address of the local machine on Linux and OS X? [closed]
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.
Solution 1:
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 '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 .bashrc
to create your own command called myip
for 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 -i
for older versions of hostname
but see comments). However, this is on Linux only.
Solution 2:
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 1.0.0.0
):
ip route get 1 | awk '{print $NF;exit}'
or avoiding awk
and using Google's public DNS at 8.8.8.8
for obviousness:
ip route get 8.8.8.8 | head -1 | cut -d' ' -f8
A less reliable way: (see comment below)
hostname -I | cut -d' ' -f1