main.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/go-ping/ping"
  6. "runtime"
  7. )
  8. var (
  9. Count = 5 // ping次数,默认5次
  10. linux = true
  11. )
  12. func init() {
  13. if runtime.GOOS != "linux" {
  14. linux = false
  15. }
  16. }
  17. func main() {
  18. r := gin.Default()
  19. r.GET("/ping/:ip", func(c *gin.Context) {
  20. ip := c.Param("ip")
  21. tcpPing, err := TcpPing(ip)
  22. if err != nil {
  23. c.JSON(200, gin.H{
  24. "message": "ping error",
  25. })
  26. }
  27. c.JSON(200, gin.H{
  28. "averageDelay": tcpPing,
  29. })
  30. })
  31. r.Run(":8080")
  32. }
  33. func TcpPing(addr string) (string, error) {
  34. pinger, err := ping.NewPinger(addr)
  35. if err != nil {
  36. return "", err
  37. }
  38. if !linux {
  39. pinger.SetPrivileged(true)
  40. }
  41. pinger.Count = Count
  42. //pinger.OnRecv = func(pkt *ping.Packet) {
  43. // fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v\n",
  44. // pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
  45. //}
  46. //pinger.OnDuplicateRecv = func(pkt *ping.Packet) {
  47. // fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v ttl=%v (DUP!)\n",
  48. // pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt, pkt.Ttl)
  49. //}
  50. //pinger.OnFinish = func(stats *ping.Statistics) {
  51. // fmt.Printf("\n--- %s ping statistics ---\n", stats.Addr)
  52. // fmt.Printf("%d packets transmitted, %d packets received, %v%% packet loss\n",
  53. // stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
  54. // fmt.Printf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n",
  55. // stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
  56. //}
  57. fmt.Printf("PING %s (%s):\n", pinger.Addr(), pinger.IPAddr())
  58. err = pinger.Run() // Blocks until finished.
  59. if err != nil {
  60. return "", err
  61. }
  62. stats := pinger.Statistics() // get send/receive/rtt stats
  63. return stats.AvgRtt.String(), nil
  64. }