Handy bash one liner for getting the ip address of a host

Posted by on February 19, 2009

Something I find that I have to do in bash scripts occasionally is to grab the ip address of a specific computer. This requires a little parsing in most cases (due to cnames and multiple ipv4 addresses for a host).

The following one liner should handle all of this correctly:

host ServerName | sed -rne 's/.*has address ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/\1/p' | head -n 1

Note: Syntax error was picked up by freespace

Comments

Respond | Trackback

  1. Perhaps:

    host “$name” | sed -r ’s/.*has address ([0-9\.]+)/\1/p’ | head -n 1

  2. Is it cheating to use dig?
    $ dig +short example.com|head -n 1

  3. Another little example (using ping and sed) is:
    ping -c 1 -s 1 -t 1 SERVERNAME|sed -n “s/).*//;s/.*(//p”

    for my Fritzbox 7170 with freetz I need to change -t to -w (donnow why)

Comments

Comments: