Bash: lookup an IP for a host name, including /etc/hosts in search

22,989

Solution 1

getent uses the low-level glibc information functions to query all configured sources.

$ getent ahosts amd.com
163.181.249.32  STREAM amd.com
163.181.249.32  DGRAM  
163.181.249.32  RAW    
$ getent ahosts ipv6.google.com
2001:4860:b009::69 STREAM ipv6.l.google.com
2001:4860:b009::69 DGRAM  
2001:4860:b009::69 RAW    

Solution 2

$ gethostip localhost
localhost 127.0.0.1 7F000001
$ gethostip -d example.org
192.0.43.10

From the syslinux package, at least in Ubuntu 12.04.

Solution 3

This is super-hacky, but I've been using it for ages, and it works (for ipv4):

function ipfor() {
  ping -c 1 $1 | grep -Eo -m 1 '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}';
}

Use like: ipfor google.com

Share:
22,989

Related videos on Youtube

Stefan Dragnev
Author by

Stefan Dragnev

Updated on September 18, 2022

Comments

  • Stefan Dragnev
    Stefan Dragnev over 1 year

    Ubuntu 10.10+

    In my script I need to lookup an IP for a given host name.

    If that name is listed in /etc/hosts, then command should print IP from /etc/hosts, not from DNS server.

    What commands I tried (nslookup, dig, host), completely ignore /etc/hosts — at least for names that are not known to the DNS server.

    Note: I would prefer solution that would not require me to grep /etc/hosts by hand.

  • luis.espinal
    luis.espinal almost 10 years
    Hacky but portable. Me like.
  • Mokubai
    Mokubai over 8 years
    While this may indeed answer the question it would be good to explain how and why it does so. A command line with little or no explanation as to what it is doing may not help future visitors who might need to solve a similar problem.
  • higuita
    higuita over 8 years
    getent hosts amd.com is probably a little simpler