Ping server/domain and capture its IP on Linux

7

2

With Windows, you could ping a given domain name and capture the IP as a variable, even if no reply was received. I believe the command looked something like this:

ping domain.com
for /f "tokens=1,2 delims=[]" %%A in ('ping /n 1 /w 1 domain.com ^| find "Pinging"') do set ipaddress=%%B"`

This is basically what I am trying to do, but within a bash script rather than a batch file. I've stumbled across a lot of questions that are really close, but not quite what I am looking for. I can't seem to figure out the best way to go about this.

Any ideas?

ICE

Posted 2013-06-02T02:40:51.820

Reputation: 264

Answers

14

This should work, from the command line or in a script:

ip=$(ping -c 1 www.google.com | gawk -F'[()]' '/PING/{print $2}')
echo $ip
173.194.34.19

EXPLANATION

First the output of the ping command being parsed:

$ ping -c 1 www.google.com
PING www.google.com (173.194.40.209) 56(84) bytes of data.
64 bytes from par10s12-in-f17.1e100.net (173.194.40.209): icmp_req=1 ttl=52 time=49.8 ms

--- www.google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 49.874/49.874/49.874/0.000 ms
  • ip=$(COMMAND) : assign the output of COMMAND to the variable $ip.
  • ping -c 1 www.google.com : ping google, once.
  • gawk is a powerful scripting language that processes input line by line and fields by field.
  • -F'[()]' : -F sets gawk's field delimiter(s). Here, we are setting it to to a character class ([ ]), specifically to open and close parentheses. This means that everything until the first ) or ( will be the first field which in gawk is $1. We are only interested in the first line so we tell gawk to print the 2nd field ($2), which is the IP, only if the current line contains "PING" (/PING/).

So, the results of the whole shebang are saved as ip which you can then refer to as $ip.

terdon

Posted 2013-06-02T02:40:51.820

Reputation: 45 216

This is so elegant -- I'm using this to get the IP address from docker.for.mac.localhost so I can use scality/s3server with boto3 and prevent my mock s3 from thinking docker.for.mac is my bucket name. – AlienWebguy – 2017-12-13T23:49:29.520

1Beautiful! just what I was looking for. Thank you – ICE – 2013-06-02T03:11:37.893

4@Jim you can replace gawk with awk to make it slightly more portable. gawk might not be installed on some UNIXs but awk should always be there. – terdon – 2013-06-02T03:18:03.377

1It works like a charm! the other method I was trying with nslookup captured all ips as a single variable. It worked, but I only needed the first one.

Thank you again for your help! now I can actually move on with my script! XD – ICE – 2013-06-02T03:26:02.137