shell - Portable way to resolve host name to IP address -


i need resolve host name ip address in shell script. code must work @ least in cygwin, ubuntu , openwrt(busybox). can assumed each host have 1 ip address.

example:

  • input

    google.com 
  • output

    216.58.209.46 

edit: nslookup may seem solution, output quite unpredictable , difficult filter. here result command on 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 

if want available out-of-the-box on modern unix, use python:

pylookup() {   python -c 'import socket, sys; print socket.gethostbyname(sys.argv[1])' "$@" 2>/dev/null }  address=$(pylookup google.com) 

with respect special-purpose tools, dig far easier work nslookup, , short mode emits literal answers -- in case, ip addresses. take first address, if more 1 found:

# bash-specific idiom read -r address < <(dig +short google.com | grep -e '^[0-9.]+$') 

if need work posix sh, or broken versions of bash (such git bash, built mingw, process substitution doesn't work), might instead use:

address=$(dig +short google.com | grep -e '^[0-9.]+$' | head -n 1) 

dig available cygwin in bind-utils package; bind used dns server on unix, bind-utils (built same codebase) available unix-family operating systems well.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -