Bash One-liner to get IP address for each network interface

This one should be pretty bulletproof. Use a single ’sed’ to dump the list of all ip addresses from network interfaces showing in ifconfig.

The Input

$ ifconfig | sed -n ‘/^[A-Za-z0-9]/ {N;/dr:/{;s/.*dr://;s/ .*//;p;}}’
or even simpler with:
$ ifconfig | sed -n ’s/.*inet addr:\([0-9.]\+\)\s.*/\1/p’
(thanks to Aleksandar)

The Output:

172.16.42.42
127.0.0.1
192.168.99.1
192.168.100.1

For reference, here’s ifconfig by itself:

eth0      Link encap:Ethernet  HWaddr 00:1E:3F:CD:69:42
          inet addr:172.16.42.42  Bcast:172.16.255.255  Mask:255.255.0.0
          inet6 addr: fe80::42d:4eff:fecb:6942/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:5351044 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3289985 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:3675865462 (3.4 GiB)  TX bytes:1415455026 (1.3 GiB)
          Memory:febe0000-fec00000 

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:64 errors:0 dropped:0 overruns:0 frame:0
          TX packets:64 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:5844 (5.7 KiB)  TX bytes:5844 (5.7 KiB)

vboxnet0  Link encap:Ethernet  HWaddr 12:34:56:78:00:00
          inet addr:192.168.99.1  Bcast:192.168.99.255  Mask:255.255.255.0
          inet6 addr: fe80::42d:4eff:fecb:6942/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:57 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 b)  TX bytes:10089 (9.8 KiB)

virbr0    Link encap:Ethernet  HWaddr 11:22:33:44:55:66
          inet addr:192.168.100.1  Bcast:192.168.100.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:17 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 b)  TX bytes:3579 (3.4 KiB)
Posted by admica   @   15 June 2010

Related Posts

Like this post? Share it!

Digg Twitter StumbleUpon Delicious Technorati Facebook RSS

1 Comments

Comments
Nov 21, 2011
2:59 pm
#1 Aleksandar Kostadinov :

How is this better than something simple like:
# ifconfig | sed -n ’s/.*inet addr:\([0-9.]\+\)\s.*/\1/p’

Leave a Comment

Name

Email

Website

Previous Post
« EVE Online Planetary Interaction - Maximize Your Profit
Next Post
Dan Kaminsky’s antidote to SQL Injection, Cross-site scripting, and other vulnerabilities »
Powered by Wordpress   |   Lunated designed by ZenVerse