Skip to main content

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).

Obviously that explanation is only meant to be a brief summary. You should consult the sed manual if 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:

  • Read UNIX/Linux system IP address in a shell script

    ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' |
    cut -d: -f2 | awk '{ print $1}'</div>

    Notice that this one uses an incorrect loopback filter ('127.0.0.1' should be ':127\.0\.0\.1 ') and yet my new favorite is still shorter ;)

  • Parsing IP Address from ifconfig

    ifconfig eth0 | grep “inet” | awk{print $2}| awk -F: ‘{print $2}

    Pretty reasonable, but two more pipes than mine :)

  • Setting up a 6to4 IPv6 tunnel with Debian

    ifconfig $EXTIF | grep 'inet addr' | cut -d : -f2 | cut -d ' ' -f1

    This is almost identical to how I used to do it - before I became familiar with sed ;)

  • Advance (sic) Linux commands

    ifconfig | grep -vw inet6 | grep -w inet | cut -d : -f 2 | cut -d \ -f 1

    Ok, but a little bit redundant.

  • ifconfig eth0 and awk and grep

    ifconfig eth0 | head -n 2 \
    | sed 'N;s/\n/ /;N;s/\n/ /' | awk '{print $7 " " $9 " " $5}' \
    | sed -e 's/addr://g' -e 's/Mask://g'

    Wow!! That one is particularly ugly! :|

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 ;)