Browse Source

Initial commit

arianagiroux 1 tháng trước cách đây
commit
09b87118c6
4 tập tin đã thay đổi với 59 bổ sung0 xóa
  1. 1 0
      .gitignore
  2. 1 0
      .vimrc
  3. 3 0
      go.mod
  4. 54 0
      pingstats/main.go

+ 1 - 0
.gitignore

@@ -0,0 +1 @@
+.undodir

+ 1 - 0
.vimrc

@@ -0,0 +1 @@
+nmap <leader>g :!go run %

+ 3 - 0
go.mod

@@ -0,0 +1,3 @@
+module pingstats
+
+go 1.25.6

+ 54 - 0
pingstats/main.go

@@ -0,0 +1,54 @@
+package main
+
+import "fmt"
+import (
+	"os/exec"
+	"strings"
+	"strconv"
+	"errors"
+	"flag"
+)
+
+func getPing(address string) (delay float64, err error) {
+	out, err := exec.Command("ping", address, "-c 1").Output()
+	if err != nil {
+		return -1, err
+	}
+
+	lines := strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n")
+	for i:=0;i<len(lines);i++ {
+		if strings.Contains(lines[i], "bytes from") {
+			position := strings.Index(lines[i], "time=")
+
+			before, _, success := strings.Cut(lines[i][position:], " ")
+			if ! success {
+				return -1, errors.New("Line does not match pattern!")
+			}
+			_, after, success := strings.Cut(before, "=")
+			if ! success {
+				return -1, errors.New("Line does not match pattern!")
+			}
+
+			delay, _ := strconv.ParseFloat(after, 64)
+			return delay, nil
+		}
+	}
+	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
+}