Skip to main content

One post tagged with "ipv4"

View All Tags

Finding the local IP address with ifconfig and sed

· 3 min read

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 (127.0.0.1) - 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 start of the sed command).