Recently needed a good way to fetch the IP address of each interface within a script. Tried things like:
1 |
ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}' |
and
1 |
/sbin/ifconfig | sed -n '2 p' | awk '{print $3}' |
But this is fairly ugly. So I tried:
1 |
hostname -I |
This gives a list of IP addresses but they are un-ordered so I can’t guarantee which address goes with which interface. Here’s one using “ip addr”:
1 |
ip=$(ip -f inet -o addr show eth0|cut -d\ -f 7 | cut -d/ -f 1) |
Still very messy. Finally, found the “ifdata” command which is part of the “moreutils” package. First make sure “moreutils” is installed with:
1 |
yum -y install moreutils |
Now you can query for a wide range of different information:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
Usage: ifdata [options] iface -e Reports interface existence via return code -p Print out the whole config of iface -pe Print out yes or no according to existence -pa Print out the address -pn Print netmask -pN Print network address -pb Print broadcast -pm Print mtu -ph Print out the hardware address -pf Print flags -si Print all statistics on input -sip Print # of in packets -sib Print # of in bytes -sie Print # of in errors -sid Print # of in drops -sif Print # of in fifo overruns -sic Print # of in compress -sim Print # of in multicast -so Print all statistics on output -sop Print # of out packets -sob Print # of out bytes -soe Print # of out errors -sod Print # of out drops -sof Print # of out fifo overruns -sox Print # of out collisions -soc Print # of out carrier loss -som Print # of out multicast -bips Print # of incoming bytes per second -bops Print # of outgoing bytes per second |
So here are some examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[root@host]# ifdata -pa eth0 10.210.160.53 [root@host]# ifdata -pa eth0 10.210.160.53 [root@host]# ifdata -pn eth0 255.255.224.0 [root@host]# ifdata -sip eth0 1622384587 [root@host]# ifdata -bops eth0 896 |
Overall this is much cleaner and more reliable then the earlier approaches.