Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portable way to resolve host name to IP address

Tags:

shell

sh

dns

I need to resolve a host name to an IP address in a shell script. The code must work at least in Cygwin, Ubuntu and OpenWrt(busybox). It can be assumed that each host will have only one IP address.

Example:

  • input

    google.com
    
  • output

    216.58.209.46
    

EDIT: nslookup may seem like a good solution, but its output is quite unpredictable and difficult to filter. Here is the result command on my computer (Cygwin):

>nslookup google.com
Unauthorized answer:
Serwer:  UnKnown
Address:  fdc9:d7b9:6c62::1

Name:   google.com
Addresses:  2a00:1450:401b:800::200e
          216.58.209.78
like image 826
NO_NAME Avatar asked Jul 08 '15 19:07

NO_NAME


1 Answers

I've no experience with OpenWRT or Busybox but the following one-liner will should work with a base installation of Cygwin or Ubuntu:

ipaddress=$(LC_ALL=C nslookup $host 2>/dev/null  | sed -nr '/Name/,+1s|Address(es)?: *||p')

The above works with both the Ubuntu and Windows version of nslookup. However, it only works when the DNS server replies with one IP (v4 or v6) address; if more than one address is returned the first one will be used.


Explanation

LC_ALL=C nslookup sets the LC_ALL environment variable when running the nslookup command so that the command ignores the current system locale and print its output in the command’s default language (English).

The 2>/dev/null avoids having warnings from the Windows version of nslookup about non-authoritative servers being printed.

The sed command looks for the line containing Name and then prints the following line after stripping the phrase Addresses: when there's more than one IP (v4 or 6) address -- or Address: when only one address is returned by the name server.

The -n option means lines aren't printed unless there's a p commandwhile the-r` option means extended regular expressions are used (GNU sed is the default for Cygwin and Ubuntu).

like image 75
Anthony Geoghegan Avatar answered Nov 08 '22 08:11

Anthony Geoghegan