| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- 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
- }
|