Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 599
sorin Avatar asked Nov 10 '12 13:11

sorin


People also ask

What is my localhost IP Linux?

When using “localhost” the network services are accessed through the logical network interface called loopback. The IP address of the loopback interface is 127.0. 0.1.

Which command is used to extract the IP address of the local machine in Linux?

To find out the IP address of Linux/UNIX/*BSD/macOS and Unixish system, you need to use the command called ifconfig on Unix and the ip command or hostname command on Linux. These commands used to configure the kernel-resident network interfaces and display IP address such as 10.8. 0.1 or 192.168.


1 Answers

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.

like image 193
Chris Seymour Avatar answered Nov 19 '22 04:11

Chris Seymour