hardware-tests/cmd/ping.go

57 lines
1.5 KiB
Go
Raw Normal View History

package cmd
import (
"fmt"
"github.com/go-ping/ping"
"github.com/spf13/cobra"
"git.metaunix.net/bitgoblin/hardware-tests/lib"
)
var (
host string
count int
)
var pingCmd = &cobra.Command{
Use: "ping",
Short: "Ping test.",
Long: "Uses ping to test network latency and aliveness.",
Run: func(cmd *cobra.Command, args []string) {
pinger, err := ping.NewPinger(host)
if err != nil {
panic(err)
}
pinger.Count = count
pinger.OnFinish = func(stats *ping.Statistics) {
result := fmt.Sprintf("--- %s ping statistics ---\n", stats.Addr)
result += fmt.Sprintf("%d packets transmitted, %d packets received, %v%% packet loss\n",
stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
result += fmt.Sprintf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n",
stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
// log the result if it's configured, otherwise print it out
if Log != "false" {
lib.WriteToFile(Log, result)
} else {
fmt.Printf("%s", result)
}
}
fmt.Printf("PING %s (%s):\n", pinger.Addr(), pinger.IPAddr())
err = pinger.Run() // Blocks until finished.
if err != nil {
panic(err)
}
},
}
func init() {
// link flags to variables
pingCmd.Flags().StringVarP(&host, "host", "a", "8.8.8.8", "Host to attempt pinging.")
pingCmd.Flags().IntVarP(&count, "count", "c", 50, "Number of pings to send.")
// add ping command to the main program
rootCmd.AddCommand(pingCmd)
}