Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Linux by (18.4k points)
I trying to find the command-line solution that would return me a primary (first) IP address of the localhost, other than 127.0.0.1

This solution should work for Linux (Debian and RedHat) and OS X 10.7+

I knew that the ifconfig is available on both but its output is not so consistent between these platforms.

1 Answer

0 votes
by (36.8k points)

Use the grep to filter your 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 the help of sed:

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

If you are interested only in certain interfaces, wlan0, eth0, etc. then:

ifconfig wlan0 | ...

You can alias your command in the .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'"

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

Come and join Linux training to gain great knowledge. 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 24, 2020 in Linux by blackindya (18.4k points)
0 votes
1 answer
asked Jan 26, 2021 in Linux by dev_sk2311 (45k points)
0 votes
1 answer

Browse Categories

...