1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package main
import (
"net"
"os/exec"
"strconv"
"strings"
)
// Ping sends one ICMP echo packet to the given IP and times how long
// it takes to get a response, in milleseconds. Returns -1 if no
// response is received.
func Ping(ip net.IP) float64 {
cmd := exec.Command("ping",
"-n", // numeric
"-q", // quiet
"-c", "1",
ip.String())
_output, _ := cmd.CombinedOutput()
output := string(_output)
for _, line := range strings.Split(output, "\n") {
if !strings.HasPrefix(line, "rtt min/avg/max/mdev = ") {
continue
}
values := strings.TrimPrefix(line, "rtt min/avg/max/mdev = ")
value, err := strconv.ParseFloat(strings.Split(values, "/")[0], 64)
if err != nil {
continue
}
return value
}
return -1
}
|