[buug] get IP address and ping ...

Michael Paoli Michael.Paoli at cal.berkeley.edu
Thu Aug 15 20:46:23 PDT 2019


Semi-random question came up at meeting today.
Question was essentially get IP address on the host, and ping it,
so, I came up with fairly quick example:
$ ping -n -c 3 $(ip a s | sed -ne '/br0/,/^5:/{/inet/{s/^[      ]*inet  
\([^ \/]*\).*$/\1/p;q}}')
PING 198.144.194.235 (198.144.194.235) 56(84) bytes of data.
64 bytes from 198.144.194.235: icmp_seq=1 ttl=64 time=0.121 ms
64 bytes from 198.144.194.235: icmp_seq=2 ttl=64 time=0.093 ms
64 bytes from 198.144.194.235: icmp_seq=3 ttl=64 time=0.085 ms

--- 198.144.194.235 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2048ms
rtt min/avg/max/mdev = 0.085/0.099/0.121/0.019 ms
$

That first uses the ip command, with the a and s arguments, get and
show the addresses.
I then pipe that to sed, the streaming editor ... I use that to whittle
the output down to just the IP address of interest ... in this case I know
it's on interface br0, so I grab that chunk of output lines - from the first
match of a line with br0 in it, through ... well, I cut it off at start
of the next interface - but as long as I get "enough" of the lines, that
would work.
Within that, I then grab the first line with inet (IPv4 address),
and toss out the stuff on that line before and after the  IP address,
print just the IP address part, then quite sed after that.
I then put all that within command substitution $() - so that -
just the resultant IP address, is substituted on the line.
And the rest is just some options and option arguments I
also pass to ping - -n for numeric (don't try to do "reverse" DNS
lookup(s) of the IP address(es)), -c 3 for count - 3 just send 3 packets
and see what we get from that.  That's basically it for that command.




More information about the buug mailing list