Friday, February 20, 2009

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

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:
[bash]
host ServerName | sed -rne 's/.*has address ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/\1/p' | head -n 1
[/bash]

Note: Syntax error was picked up by freespace

3 comments:

  1. Perhaps:

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

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

    ReplyDelete
  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)

    ReplyDelete