diff options
author | Luke Shumaker <lukeshu@lukeshu.com> | 2018-04-17 16:21:34 -0400 |
---|---|---|
committer | Luke Shumaker <lukeshu@lukeshu.com> | 2018-04-17 16:21:34 -0400 |
commit | 6cdcdc77871f9c08be4f4f50d52cb178c429d203 (patch) | |
tree | ec0a1c15da5b885addb6e114663430ee7f8614da | |
parent | d18e052e01ec6fa6df4165a409058fb81adf0555 (diff) |
add ping
-rw-r--r-- | main.go | 44 | ||||
-rw-r--r-- | ping.go | 30 |
2 files changed, 67 insertions, 7 deletions
@@ -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() { @@ -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 +} |