0

I need the IP (v4) address of a device I specify. The response will be later used in a script. This is what I have:

$ IFACE=eth1
$ ifconfig $IFACE |grep "inet " | awk '{print $2}'
10.0.0.33

Is there a cleaner (shorter) way of doing this?

EDIT: ifdata is exactly what I need. Solution found here: https://unix.stackexchange.com/a/84263/126008

1 Answers1

2

It's neither cleaner, nor shorter really, but I think you should use ip instead of ifconfig. It's current, maintained, and perhaps more importantly for your purpose, it produces a consistent & parsable output.

If you want the IPv4 address for eth0:

$ ip -4 -o addr show eth0 | awk '{print $4}'
192.168.1.166/24  

which is in CIDR notation. If CIDR notation isn't wanted it can be stripped:

$ ip -4 -o addr show eth0 | awk '{print $4}' | cut -d "/" -f 1 
192.168.1.166  

Your question specified you wanted an address for an interface you specified. I think the answers above provide that, but if you want the IPv4 address for the host you're on, perhaps hostname is easier/more concise:

$ hostname --all-ip-addresses | awk '{print $1}'  

Or, if you want the IPv6 address:

$ hostname --all-ip-addresses | awk '{print $2}'  

Finally, one other option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:

$ ip route get 8.8.8.8 | awk '{ print $NF; exit }'
192.168.1.166

As a script:

$ RHOST=8.8.8.8  
$ ip route get $RHOST | awk '{ print $NF; exit }'

Which could be useful on a host with multiple interfaces and route specifications.

Seamus
  • 2,925