Finding the local IP address with ifconfig and sed

There are many ways to determine local IP addresses on Linux platforms. They almost always involve piping ifconfig into a number of grep, awk, cat, and/or tr commands.

Well, my new favorite approach is to pipe ifconfig into a single sed command :)

ifconfig | sed -n -e 's/:127\.0\.0\.1 //g' -e 's/ *inet addr:\([0-9.]\+\).*/\1/gp'

Neat, huh?! :)

So, how does it work? Well, there are two filters (aka scripts, ie the parameters after the -e flags). The first one, s/:127\.0\.0\.1 //g', simply strips out all occurrences of the local loopback address ( - this can be left out if you want to include the loopback address in the results. And the second filter, 's/ *inet addr:\([0-9.]\+\).*/\1/gp' matches all lines with IP addresses, strips all but the IP address itself, and prints the matching line (note the 'p' at the end of the filter, which works in with the -n flag at the stared of the sed command).

Obviously that explanation is only meant to be a brief summary. You should consult the sed manual is you're still unsure of how / why this works... or post a question below :)

Just for comparison, here's some examples of how others do the same thing:

So you can see there are many ways to parse the local IP addresses from ifconfig's output. In the end, the one that works best for you will depend on a number of things, including which utility commands are available on your local system. But as long sed is available, my command at the top will be my favourite... well, at least until my next favourite comes along ;)

comments powered by Disqus