Resolve hostname to ip address in shell

Many a times you require to create shell or bash scripts to fetch ip address from hostnames. There are multiple ways to do this, i am listing down here this ways it can be done from.

Use getent, which is part of  glibc so you will definitely have it in linux. This works using functions gethostbyaddr,gethostbyname2. This may also check /etc/host/ to give the required results.

getent hosts | awk '{ print $1 }'

Second way to do this is using dig with the +short argument, this will query DNS servers directly, and won’t look in  at /etc/hosts/NSS/etc.

dig +short

Many a times you may find that dig +short is not present in your custom linux, then any one of the following should work. All of these will query DNS directly and wont look anywhere else for ip resolution.

host | awk '/ip address is/ { print $4 }'
nslookup | awk '/^ip Address is: / { print $2 }'
dig | awk '/^;; IP address is:$/ { getline ; print $5 }'

To print only one IP address add the exit command to awk’s workflow.

dig +short | awk '{ print ; exit }'
getent hosts | awk '{ print $1 ; exit }'
host | awk '/IP address/ { print $4 ; exit }'
nslookup | awk '/^IP Address: / { print $2 ; exit }'
dig | awk '/^;; IP address is:$/ { getline ; print $5 ; exit }'
This entry was posted in linux. Bookmark the permalink.