main.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package main
  2. import "fmt"
  3. import (
  4. "os/exec"
  5. "strings"
  6. "strconv"
  7. "errors"
  8. "flag"
  9. )
  10. func getPing(address string) (delay float64, err error) {
  11. out, err := exec.Command("ping", address, "-c 1").Output()
  12. if err != nil {
  13. return -1, err
  14. }
  15. lines := strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n")
  16. for i:=0;i<len(lines);i++ {
  17. if strings.Contains(lines[i], "bytes from") {
  18. position := strings.Index(lines[i], "time=")
  19. before, _, success := strings.Cut(lines[i][position:], " ")
  20. if ! success {
  21. return -1, errors.New("Line does not match pattern!")
  22. }
  23. _, after, success := strings.Cut(before, "=")
  24. if ! success {
  25. return -1, errors.New("Line does not match pattern!")
  26. }
  27. delay, _ := strconv.ParseFloat(after, 64)
  28. return delay, nil
  29. }
  30. }
  31. return -1, errors.New("could not resolve host: " + address)
  32. }
  33. func main() {
  34. flag.Parse()
  35. hosts := flag.Args()
  36. if len(hosts) == 0 {
  37. fmt.Println("Must specify hosts!")
  38. return
  39. }
  40. for i:=0;i<len(hosts);i++ {
  41. ping, _ := getPing(hosts[i])
  42. fmt.Printf("%s:\t%f\n", hosts[i], ping)
  43. }
  44. return
  45. }