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
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With