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 techonicals.com | 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 c.com

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 techonicals.com | awk '/ip address is/ { print $4 }'
nslookup techonicals.com | awk '/^ip Address is: / { print $2 }'
dig techonicals.com | awk '/^;; IP address is:$/ { getline ; print $5 }'

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

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