Updated : Mar 20, 2015 in Bash

Resolve the IP from a hostname

As a Linux administrator I often need to resolve hostnames into IPs specially in scripts. Using the command ‘host’ the sytem will resolve the IP only through the resolver libraries omitting to look into the /etc/hosts file. The same is true for the command ‘nslookup’ and ‘dig’. A good trick is to use the command ‘ping’ which starts the resolving at the /etc/hosts and then the resolver libraries. But ping is meant to send a ping (at least one) and what if don’t want to send a ping. Here is a good suggestion for it based on:
http://unix.stackexchange.com/questions/20784/how-can-i-resolve-a-hostname-to-an-ip-address-in-a-bash-script

All following commands will resolve an IP address if the host still exist according to the configuration in /etc/nsswitch.conf which generally means the following lookup sequence:
– Look in /etc/hosts
– If not found in /etc/hosts, then query the system resolver libraries which ask the configured DNSs in /etc/resolv.conf.

If host points to CNAME it will also get the IP in that case.

Resolves to IPv4 address:
getent ahostsv4 www.google.de | grep STREAM | head -n 1 | cut -d ' ' -f 1

Resolves to IPv6 address
getent ahostsv6 www.google.de | grep STREAM | head -n 1 | cut -d ' ' -f 1

Will return the owners preferred address what may IPv4 or IPv6 address:
getent hosts google.de | head -n 1 | cut -d ' ' -f 1

Getting the zone info for a domain

dig +nocmd {domain} any +multiline +noall +answer [@NAMESERVER]
eg.
dig +nocmd itmatrix.de any +multiline +noall +answer @nsc1.schlundtech.de.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: