Try something like
export IP=`( dig ${HOSTNAME} A +short | tail -n1; \
dig ${HOSTNAME} AAAA +short | tail -n1 ) \
| head -n1`
This will give you:
- For a host with at least one IPv4 address, (one of) the IPv4 address
- For a host with no IPv4 addresses but with at least one IPv6 address, (one of) the IPv6 address
- For a host with no (IPv4 or IPv6) address at all in DNS, or if there is a resolver failure, an empty value
If you don't need IPv4 or IPv6 capability (your question seems to indicate you are mostly interested in the IPv4 address), just remove that dig
command (A
is IPv4, AAAA
is IPv6). So, if you are only interested in IPv4 addresses:
export IP=`dig ${HOSTNAME} A +short | tail -n1`
The tail -n1
ensures that you get an IP address (in the case of CNAME
, and possibly other record types, dig
outputs the referenced canonical name on the first line). The head -n1
ensures that you only get a single address by returning only the first line of the remaining output (unnecessary in the case of only one address family, since tail
will return only one address). Since DNS records are normally served in a round-robin fashion, there is no guarantee which exact address will be returned for multiple-address hosts.
I'm not too familiar with writing bash functions, but it should be relatively easy to turn this into a function.
#3 is a very different question from the other two, and as it currently stands, extremely broad. I doubt that can even be answered in a good way as it is written now. – a CVn – 2012-07-17T12:51:47.943