|
|
@@ -1,21 +1,44 @@
|
|
|
-package main
|
|
|
+// defines basic mechanics for pingstats
|
|
|
+package ping
|
|
|
|
|
|
-import "fmt"
|
|
|
import (
|
|
|
"os/exec"
|
|
|
"strings"
|
|
|
"strconv"
|
|
|
"errors"
|
|
|
- "flag"
|
|
|
)
|
|
|
|
|
|
-func getPing(address string) (delay float64, err error) {
|
|
|
+// runPing returns the byte array as returned by [exec.Command]
|
|
|
+//
|
|
|
+// NOTE(os): this function may fail on non-unix compliant implementations of the Ping spec.
|
|
|
+func runPing(address string) (delay *[]byte, err error){
|
|
|
out, err := exec.Command("ping", address, "-c 1").Output()
|
|
|
+ if err != nil {
|
|
|
+ return nil, err
|
|
|
+ }
|
|
|
+ return &out, err
|
|
|
+}
|
|
|
+
|
|
|
+// splitBytesToLines splits bytes as returned by [pingstats.runPing] into an
|
|
|
+// array of strings by newline
|
|
|
+func splitBytesToLines(bytes *[]byte) (lines []string) {
|
|
|
+ return strings.Split(strings.ReplaceAll(string(*bytes), "\r\n", "\n"), "\n")
|
|
|
+}
|
|
|
+
|
|
|
+// Ping returns the delay of a single Ping as reported by the system Ping binary.
|
|
|
+//
|
|
|
+// If the function is unable to resolve the system binary output or fails to
|
|
|
+// successfully resolve a Ping, it will always return -1.
|
|
|
+//
|
|
|
+// NOTE(os): this function may fail on non-unix compliant implementations of the Ping spec.
|
|
|
+func Ping(address string) (delay float64, err error) {
|
|
|
+ out, err := runPing(address)
|
|
|
if err != nil {
|
|
|
return -1, err
|
|
|
}
|
|
|
|
|
|
- lines := strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n")
|
|
|
+ lines := splitBytesToLines(out)
|
|
|
+
|
|
|
for i:=0;i<len(lines);i++ {
|
|
|
if strings.Contains(lines[i], "bytes from") {
|
|
|
position := strings.Index(lines[i], "time=")
|
|
|
@@ -35,20 +58,3 @@ func getPing(address string) (delay float64, err error) {
|
|
|
}
|
|
|
return -1, errors.New("could not resolve host: " + address)
|
|
|
}
|
|
|
-
|
|
|
-func main() {
|
|
|
- flag.Parse()
|
|
|
- hosts := flag.Args()
|
|
|
-
|
|
|
- if len(hosts) == 0 {
|
|
|
- fmt.Println("Must specify hosts!")
|
|
|
- return
|
|
|
- }
|
|
|
-
|
|
|
- for i:=0;i<len(hosts);i++ {
|
|
|
- ping, _ := getPing(hosts[i])
|
|
|
- fmt.Printf("%s:\t%f\n", hosts[i], ping)
|
|
|
- }
|
|
|
-
|
|
|
- return
|
|
|
-}
|