From 6cdcdc77871f9c08be4f4f50d52cb178c429d203 Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Tue, 17 Apr 2018 16:21:34 -0400 Subject: add ping --- main.go | 44 +++++++++++++++++++++++++++++++++++++------- ping.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 7 deletions(-) create mode 100644 ping.go diff --git a/main.go b/main.go index 9717040..eba5024 100644 --- a/main.go +++ b/main.go @@ -63,21 +63,51 @@ func DoAddress(host, network, address string) Point { } return NewPoint("public", tags, map[string]interface{}{"error": err.Error()}) } - conn, err := net.DialTCP(network, nil, addr) + + var _wg sync.WaitGroup + _wg.Add(2) + var result_name string + var result_version string + var result_error error + go func() { + defer _wg.Done() + result_name, result_version, result_error = Hello(addr) + }() + var result_ping float64 + go func() { + defer _wg.Done() + result_ping = Ping(addr.IP) + }() + _wg.Wait() + + result := map[string]interface{}{} + if result_error == nil { + result["name"] = result_name + result["version"] = result_version + } else { + result["error"] = result_error + } + if result_ping >= 0 { + result["ping"] = result_ping + } + + return NewPoint("public", tags, result) +} + +func Hello(addr *net.TCPAddr) (name, version string, err error) { + conn, err := net.DialTCP(addr.Network(), nil, addr) if err != nil { - return NewPoint("public", tags, map[string]interface{}{"error": err.Error()}) + return "", "", err } + defer conn.Close() conn.CloseWrite() all, _ := ioutil.ReadAll(conn) line := strings.TrimRight(string(all), "\n") parts := strings.Split(line, " ") if len(parts) != 3 { - return NewPoint("public", tags, map[string]interface{}{"error": fmt.Sprintf("malformed ID line: %q", line)}) + return "", "", fmt.Errorf("malformed ID line: %q", line) } - return NewPoint("public", tags, map[string]interface{}{ - "name": parts[1], - "version": parts[2], - }) + return parts[1], parts[2], nil } func main() { diff --git a/ping.go b/ping.go new file mode 100644 index 0000000..a41b4ab --- /dev/null +++ b/ping.go @@ -0,0 +1,30 @@ +package main + +import ( + "net" + "os/exec" + "strconv" + "strings" +) + +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 +} -- cgit v1.2.3-2-g168b