package main import ( "fmt" "github.com/gin-gonic/gin" "github.com/go-ping/ping" "runtime" ) var ( Count = 5 // ping次数,默认5次 linux = true ) func init() { if runtime.GOOS != "linux" { linux = false } } func main() { r := gin.Default() r.GET("/ping/:ip", func(c *gin.Context) { ip := c.Param("ip") tcpPing, err := TcpPing(ip) if err != nil { c.JSON(200, gin.H{ "message": "ping error", }) } c.JSON(200, gin.H{ "averageDelay": tcpPing, }) }) r.Run(":8080") } func TcpPing(addr string) (string, error) { pinger, err := ping.NewPinger(addr) if err != nil { return "", err } if !linux { pinger.SetPrivileged(true) } pinger.Count = Count //pinger.OnRecv = func(pkt *ping.Packet) { // fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v\n", // pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt) //} //pinger.OnDuplicateRecv = func(pkt *ping.Packet) { // fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v ttl=%v (DUP!)\n", // pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt, pkt.Ttl) //} //pinger.OnFinish = func(stats *ping.Statistics) { // fmt.Printf("\n--- %s ping statistics ---\n", stats.Addr) // fmt.Printf("%d packets transmitted, %d packets received, %v%% packet loss\n", // stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss) // fmt.Printf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n", // stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt) //} fmt.Printf("PING %s (%s):\n", pinger.Addr(), pinger.IPAddr()) err = pinger.Run() // Blocks until finished. if err != nil { return "", err } stats := pinger.Statistics() // get send/receive/rtt stats return stats.AvgRtt.String(), nil }