ping.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. // Package probing is a simple but powerful ICMP echo (ping) library.
  2. //
  3. // Here is a very simple example that sends and receives three packets:
  4. //
  5. // pinger, err := probing.NewPinger("www.google.com")
  6. // if err != nil {
  7. // panic(err)
  8. // }
  9. // pinger.Count = 3
  10. // err = pinger.Run() // blocks until finished
  11. // if err != nil {
  12. // panic(err)
  13. // }
  14. // stats := pinger.Statistics() // get send/receive/rtt stats
  15. //
  16. // Here is an example that emulates the traditional UNIX ping command:
  17. //
  18. // pinger, err := probing.NewPinger("www.google.com")
  19. // if err != nil {
  20. // panic(err)
  21. // }
  22. // // Listen for Ctrl-C.
  23. // c := make(chan os.Signal, 1)
  24. // signal.Notify(c, os.Interrupt)
  25. // go func() {
  26. // for _ = range c {
  27. // pinger.Stop()
  28. // }
  29. // }()
  30. // pinger.OnRecv = func(pkt *probing.Packet) {
  31. // fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v\n",
  32. // pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
  33. // }
  34. // pinger.OnFinish = func(stats *probing.Statistics) {
  35. // fmt.Printf("\n--- %s ping statistics ---\n", stats.Addr)
  36. // fmt.Printf("%d packets transmitted, %d packets received, %v%% packet loss\n",
  37. // stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
  38. // fmt.Printf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n",
  39. // stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
  40. // }
  41. // fmt.Printf("PING %s (%s):\n", pinger.Addr(), pinger.IPAddr())
  42. // err = pinger.Run()
  43. // if err != nil {
  44. // panic(err)
  45. // }
  46. //
  47. // It sends ICMP Echo Request packet(s) and waits for an Echo Reply in response.
  48. // If it receives a response, it calls the OnRecv callback. When it's finished,
  49. // it calls the OnFinish callback.
  50. //
  51. // For a full ping example, see "cmd/ping/ping.go".
  52. package probing
  53. import (
  54. "errors"
  55. "fmt"
  56. "math"
  57. "math/rand"
  58. "net"
  59. "sync"
  60. "sync/atomic"
  61. "time"
  62. "trial/ping/probing/icmp"
  63. "github.com/google/uuid"
  64. "golang.org/x/sync/errgroup"
  65. )
  66. var receive_buffer_count = mcfg.GetInt("ping.recv.buf.count", 10)
  67. var ping_ttl = mcfg.GetInt("ping.ttl", 64)
  68. var ping_interval = mcfg.GetDuration("ping.interval", 1000*time.Millisecond)
  69. var concurlimit_ping = mcfg.GetInt("concurlimit.ping", 100)
  70. var concurchan_ping = make(chan struct{}, concurlimit_ping)
  71. var lastpingtimemutex sync.Mutex
  72. var lastpingtime = map[string]time.Time{}
  73. var ETIMEDOUT error = fmt.Errorf("timeout")
  74. const (
  75. timeSliceLength = 8
  76. trackerLength = len(uuid.UUID{})
  77. )
  78. // New returns a new Pinger struct pointer.
  79. func New(addr string) *Pinger {
  80. r := rand.New(rand.NewSource(getSeed()))
  81. return &Pinger{
  82. Count: -1,
  83. Interval: time.Second,
  84. RecordRtts: true,
  85. Size: timeSliceLength + trackerLength,
  86. Timeout: time.Duration(math.MaxInt64),
  87. addr: addr,
  88. done: make(chan interface{}),
  89. id: r.Intn(math.MaxUint16),
  90. ipaddr: nil,
  91. ipv4: false,
  92. network: "ip",
  93. protocol: "udp",
  94. }
  95. }
  96. // NewPinger returns a new Pinger and resolves the address.
  97. func NewPinger(addr string) (*Pinger, error) {
  98. p := New(addr)
  99. return p, p.Resolve()
  100. }
  101. // Pinger represents a packet sender/receiver.
  102. type Pinger struct {
  103. // Size of packet being sent
  104. Size int
  105. // Interval is the wait time between each packet send. Default is 1s.
  106. Interval time.Duration
  107. // Timeout specifies a timeout before ping exits, regardless of how many
  108. // packets have been received.
  109. Timeout time.Duration
  110. // Count tells pinger to stop after sending (and receiving) Count echo
  111. // packets. If this option is not specified, pinger will operate until
  112. // interrupted.
  113. Count int
  114. // Number of packets sent
  115. PacketsSent int
  116. // Number of packets received
  117. PacketsRecv int
  118. // Number of duplicate packets received
  119. PacketsRecvDuplicates int
  120. // Round trip time statistics
  121. minRtt time.Duration
  122. maxRtt time.Duration
  123. avgRtt time.Duration
  124. stdDevRtt time.Duration
  125. stddevm2 time.Duration
  126. statsMu sync.RWMutex
  127. // If true, keep a record of rtts of all received packets.
  128. // Set to false to avoid memory bloat for long running pings.
  129. RecordRtts bool
  130. // rtts is all of the Rtts
  131. rtts []time.Duration
  132. // OnSetup is called when Pinger has finished setting up the listening socket
  133. OnSetup func()
  134. // OnSend is called when Pinger sends a packet
  135. OnSend func(*Packet)
  136. // OnRecv is called when Pinger receives and processes a packet
  137. OnRecv func(*Packet)
  138. // OnRecv is called when Pinger receives and processes a packet
  139. OnTimeout func(*Packet)
  140. // OnFinish is called when Pinger exits
  141. OnFinish func(*Statistics)
  142. // OnDuplicateRecv is called when a packet is received that has already been received.
  143. OnDuplicateRecv func(*Packet)
  144. // Source is the source IP address
  145. Source string
  146. // Channel and mutex used to communicate when the Pinger should stop between goroutines.
  147. done chan interface{}
  148. lock sync.Mutex
  149. ipaddr *net.IPAddr
  150. addr string
  151. ipv4 bool
  152. id int
  153. sequence_base int
  154. // network is one of "ip", "ip4", or "ip6".
  155. network string
  156. // protocol is "icmp" or "udp".
  157. protocol string
  158. }
  159. // Packet represents a received and processed ICMP echo packet.
  160. type Packet struct {
  161. // Host is the string address of the host being pinged.
  162. Host string
  163. // IPAddr is the address of the host being pinged.
  164. IPAddr *net.IPAddr
  165. // ID is the ICMP identifier.
  166. ID int
  167. // Seq is the ICMP sequence number.
  168. Seq int
  169. // NBytes is the number of bytes in the message.
  170. Nbytes int
  171. // TTL is the Time To Live on the packet.
  172. TTL int
  173. // Rtt is the round-trip time it took to ping.
  174. Rtt time.Duration
  175. }
  176. // Statistics represent the stats of a currently running or finished
  177. // pinger operation.
  178. type Statistics struct {
  179. // PacketsRecv is the number of packets received.
  180. PacketsRecv int
  181. // PacketsSent is the number of packets sent.
  182. PacketsSent int
  183. // PacketsRecvDuplicates is the number of duplicate responses there were to a sent packet.
  184. PacketsRecvDuplicates int
  185. // PacketLoss is the percentage of packets lost.
  186. PacketLoss float64
  187. // IPAddr is the address of the host being pinged.
  188. IPAddr *net.IPAddr
  189. // Addr is the string address of the host being pinged.
  190. Addr string
  191. // Rtts is all of the round-trip times sent via this pinger.
  192. Rtts []time.Duration
  193. // MinRtt is the minimum round-trip time sent via this pinger.
  194. MinRtt time.Duration
  195. // MaxRtt is the maximum round-trip time sent via this pinger.
  196. MaxRtt time.Duration
  197. // AvgRtt is the average round-trip time sent via this pinger.
  198. AvgRtt time.Duration
  199. // StdDevRtt is the standard deviation of the round-trip times sent via
  200. // this pinger.
  201. StdDevRtt time.Duration
  202. }
  203. func (p *Pinger) updateStatistics(pkt *Packet) {
  204. p.statsMu.Lock()
  205. defer p.statsMu.Unlock()
  206. p.PacketsRecv++
  207. if p.RecordRtts {
  208. p.rtts = append(p.rtts, pkt.Rtt)
  209. }
  210. if p.PacketsRecv == 1 || pkt.Rtt < p.minRtt {
  211. p.minRtt = pkt.Rtt
  212. }
  213. if pkt.Rtt > p.maxRtt {
  214. p.maxRtt = pkt.Rtt
  215. }
  216. pktCount := time.Duration(p.PacketsRecv)
  217. // welford's online method for stddev
  218. // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
  219. delta := pkt.Rtt - p.avgRtt
  220. p.avgRtt += delta / pktCount
  221. delta2 := pkt.Rtt - p.avgRtt
  222. p.stddevm2 += delta * delta2
  223. p.stdDevRtt = time.Duration(math.Sqrt(float64(p.stddevm2 / pktCount)))
  224. }
  225. // SetIPAddr sets the ip address of the target host.
  226. func (p *Pinger) SetIPAddr(ipaddr *net.IPAddr) {
  227. p.ipv4 = isIPv4(ipaddr.IP)
  228. p.ipaddr = ipaddr
  229. p.addr = ipaddr.String()
  230. }
  231. // IPAddr returns the ip address of the target host.
  232. func (p *Pinger) IPAddr() *net.IPAddr {
  233. return p.ipaddr
  234. }
  235. // Resolve does the DNS lookup for the Pinger address and sets IP protocol.
  236. func (p *Pinger) Resolve() error {
  237. if len(p.addr) == 0 {
  238. return errors.New("addr cannot be empty")
  239. }
  240. ipaddr, err := net.ResolveIPAddr(p.network, p.addr)
  241. if err != nil {
  242. return err
  243. }
  244. p.ipv4 = isIPv4(ipaddr.IP)
  245. p.ipaddr = ipaddr
  246. return nil
  247. }
  248. // SetAddr resolves and sets the ip address of the target host, addr can be a
  249. // DNS name like "www.google.com" or IP like "127.0.0.1".
  250. func (p *Pinger) SetAddr(addr string) error {
  251. oldAddr := p.addr
  252. p.addr = addr
  253. err := p.Resolve()
  254. if err != nil {
  255. p.addr = oldAddr
  256. return err
  257. }
  258. return nil
  259. }
  260. // Addr returns the string ip address of the target host.
  261. func (p *Pinger) Addr() string {
  262. return p.addr
  263. }
  264. // SetNetwork allows configuration of DNS resolution.
  265. // * "ip" will automatically select IPv4 or IPv6.
  266. // * "ip4" will select IPv4.
  267. // * "ip6" will select IPv6.
  268. func (p *Pinger) SetNetwork(n string) {
  269. switch n {
  270. case "ip4":
  271. p.network = "ip4"
  272. case "ip6":
  273. p.network = "ip6"
  274. default:
  275. p.network = "ip"
  276. }
  277. }
  278. /*
  279. https://stackoverflow.com/questions/41423637/go-ping-library-for-unprivileged-icmp-ping-in-golang/41425527#41425527
  280. This library attempts to send an "unprivileged" ping via UDP. On linux, this must be enabled by setting
  281. sudo sysctl -w net.ipv4.ping_group_range="0 2147483647"
  282. If you do not wish to do this, you can set pinger.SetPrivileged(true) and use setcap to allow your binary using go-ping to bind to raw sockets (or just run as super-user):
  283. setcap cap_net_raw=+ep /bin/goping-binary
  284. getcap /bin/goping-binary to validate
  285. */
  286. // SetPrivileged sets the type of ping pinger will send.
  287. // false means pinger will send an "unprivileged" UDP ping.
  288. // true means pinger will send a "privileged" raw ICMP ping.
  289. // NOTE: setting to true requires that it be run with super-user privileges.
  290. func (p *Pinger) SetPrivileged(privileged bool) {
  291. if privileged {
  292. p.protocol = "icmp"
  293. } else {
  294. p.protocol = "udp"
  295. }
  296. }
  297. // Privileged returns whether pinger is running in privileged mode.
  298. func (p *Pinger) Privileged() bool {
  299. return p.protocol == "icmp"
  300. }
  301. // SetID sets the ICMP identifier.
  302. func (p *Pinger) SetID(id int) {
  303. p.id = id
  304. }
  305. // ID returns the ICMP identifier.
  306. func (p *Pinger) ID() int {
  307. return p.id
  308. }
  309. var pingipmtx sync.Mutex
  310. var pingips = map[string]chan interface{}{}
  311. var pingads = map[string]chan interface{}{}
  312. // Run runs the pinger. This is a blocking function that will exit when it's
  313. // done. If Count or Interval are not specified, it will run continuously until
  314. // it is interrupted.
  315. func (p *Pinger) Run() (err error) {
  316. // 同一地址,只能有一个实例运行,排队等待
  317. pingipmtx.Lock()
  318. pingipchan := pingips[p.ipaddr.String()]
  319. if pingipchan == nil {
  320. pingipchan = make(chan interface{}, 1)
  321. pingips[p.ipaddr.String()] = pingipchan
  322. }
  323. pingadchan := pingads[p.addr]
  324. if pingadchan == nil {
  325. pingadchan = make(chan interface{}, 1)
  326. pingads[p.addr] = pingadchan
  327. }
  328. pingipmtx.Unlock()
  329. pingipchan <- 1
  330. pingadchan <- 1
  331. var last_send_time time.Time
  332. defer func() {
  333. d := p.Interval - time.Since(last_send_time)
  334. if d > 0 {
  335. time.Sleep(d) // 两次运行之间至少间隔
  336. }
  337. <-pingipchan
  338. <-pingadchan
  339. }()
  340. // sleeptime := time.Duration(0)
  341. // for sleeptime >= 0 {
  342. // time.Sleep(sleeptime)
  343. // lastpingtimemutex.Lock()
  344. // alastpingtime := lastpingtime[p.ipaddr.String()]
  345. // sleeptime = ping_interval_one_host - time.Since(alastpingtime)
  346. // if sleeptime <= 0 {
  347. // lastpingtime[p.ipaddr.String()] = time.Now()
  348. // } else {
  349. // // logger.Error(fmt.Sprint("ping", p.addr, "[", p.ipaddr.String(), "]", "同一地址至少间隔一秒"))
  350. // }
  351. // lastpingtimemutex.Unlock()
  352. // }
  353. // defer func() {
  354. // lastpingtimemutex.Lock()
  355. // lastpingtime[p.ipaddr.String()] = time.Now()
  356. // lastpingtimemutex.Unlock()
  357. // }()
  358. // concurchan_ping <- struct{}{}
  359. // defer func() {
  360. // <-concurchan_ping
  361. // }()
  362. last_send_time, err = p.run()
  363. return
  364. }
  365. func (p *Pinger) run() (time.Time, error) {
  366. defer p.finish()
  367. err := MPConn(p.ipv4, p.protocol).Listen()
  368. if err != nil {
  369. return time.Time{}, err
  370. }
  371. if handler := p.OnSetup; handler != nil {
  372. handler()
  373. }
  374. var g errgroup.Group
  375. var last_send_time time.Time
  376. g.Go(func() (err error) {
  377. defer p.Stop()
  378. last_send_time, err = p.runLoop()
  379. return err
  380. })
  381. return last_send_time, g.Wait()
  382. }
  383. func (p *Pinger) runLoop() (time.Time, error) {
  384. timeout := time.NewTimer(p.Timeout)
  385. interval := time.NewTimer(0)
  386. timeout.Stop()
  387. defer func() {
  388. interval.Stop()
  389. timeout.Stop()
  390. }()
  391. received := make(chan interface{}, 1)
  392. last_send_time := time.Now()
  393. pinfo := getPingInfo(p.ipaddr)
  394. pinfo.host = p.addr
  395. pinfo.size = p.Size
  396. pinfo.timeout = p.Timeout
  397. pinfo.OnSend = func(pkt *icmp.Packet) {
  398. last_send_time = pkt.SendTime
  399. if p.PacketsSent == 0 {
  400. p.sequence_base = pkt.Seq
  401. }
  402. p.PacketsSent++
  403. if p.OnSend != nil {
  404. p.OnSend(&Packet{
  405. Host: p.addr,
  406. IPAddr: pkt.IPAddr,
  407. ID: pkt.ID,
  408. Seq: pkt.Seq - p.sequence_base,
  409. Nbytes: pkt.Nbytes,
  410. TTL: pkt.TTL,
  411. Rtt: pkt.Rtt,
  412. })
  413. }
  414. }
  415. pinfo.OnRecv = func(pkt *icmp.Packet) {
  416. inpkt := &Packet{
  417. Host: p.addr,
  418. IPAddr: pkt.IPAddr,
  419. ID: pkt.ID,
  420. Seq: pkt.Seq - p.sequence_base,
  421. Nbytes: pkt.Nbytes,
  422. TTL: pkt.TTL,
  423. Rtt: pkt.Rtt,
  424. }
  425. if p.OnRecv != nil {
  426. p.OnRecv(inpkt)
  427. }
  428. p.updateStatistics(inpkt)
  429. received <- nil
  430. }
  431. pinfo.OnRecvDup = func(pkt *icmp.Packet) {
  432. inpkt := &Packet{
  433. Host: p.addr,
  434. IPAddr: pkt.IPAddr,
  435. ID: pkt.ID,
  436. Seq: pkt.Seq - p.sequence_base,
  437. Nbytes: pkt.Nbytes,
  438. TTL: pkt.TTL,
  439. Rtt: pkt.Rtt,
  440. }
  441. if p.OnDuplicateRecv != nil {
  442. p.OnDuplicateRecv(inpkt)
  443. }
  444. p.updateStatistics(inpkt)
  445. }
  446. for {
  447. select {
  448. case <-p.done:
  449. return last_send_time, nil
  450. case <-timeout.C:
  451. return last_send_time, nil
  452. case <-interval.C:
  453. if p.Count > 0 && p.PacketsSent >= p.Count {
  454. timeout.Reset(p.Timeout)
  455. } else {
  456. if err := MPConn(p.ipv4, p.protocol).Ping(pinfo); err != nil {
  457. logger.Errorf("sending packet: %s", err)
  458. }
  459. interval.Reset(p.Interval)
  460. }
  461. case <-received:
  462. if p.Count > 0 && p.PacketsRecv >= p.Count {
  463. return last_send_time, nil
  464. }
  465. }
  466. }
  467. }
  468. // func (p *Pinger) ping(pinfo *mpinfo, received chan interface{}) error {
  469. // sleeptime := time.Duration(0)
  470. // for sleeptime >= 0 {
  471. // time.Sleep(sleeptime)
  472. // lastpingtimemutex.Lock()
  473. // alastpingtime := lastpingtime[p.ipaddr.String()]
  474. // sleeptime = ping_interval - time.Since(alastpingtime)
  475. // if sleeptime <= 0 {
  476. // lastpingtime[p.ipaddr.String()] = time.Now()
  477. // } else {
  478. // // logger.Error(fmt.Sprint("ping", p.addr, "[", p.ipaddr.String(), "]", "同一地址至少间隔一秒"))
  479. // }
  480. // lastpingtimemutex.Unlock()
  481. // }
  482. // defer func() {
  483. // lastpingtimemutex.Lock()
  484. // lastpingtime[p.ipaddr.String()] = time.Now()
  485. // lastpingtimemutex.Unlock()
  486. // }()
  487. // return MPConn(p.ipv4, p.protocol).Ping(pinfo)
  488. // }
  489. func (p *Pinger) Stop() {
  490. p.lock.Lock()
  491. defer p.lock.Unlock()
  492. open := true
  493. select {
  494. case _, open = <-p.done:
  495. default:
  496. }
  497. if open {
  498. close(p.done)
  499. }
  500. }
  501. func (p *Pinger) finish() {
  502. handler := p.OnFinish
  503. if handler != nil {
  504. s := p.Statistics()
  505. handler(s)
  506. }
  507. }
  508. // Statistics returns the statistics of the pinger. This can be run while the
  509. // pinger is running or after it is finished. OnFinish calls this function to
  510. // get it's finished statistics.
  511. func (p *Pinger) Statistics() *Statistics {
  512. p.statsMu.RLock()
  513. defer p.statsMu.RUnlock()
  514. sent := p.PacketsSent
  515. loss := float64(sent-p.PacketsRecv) / float64(sent) * 100
  516. s := Statistics{
  517. PacketsSent: sent,
  518. PacketsRecv: p.PacketsRecv,
  519. PacketsRecvDuplicates: p.PacketsRecvDuplicates,
  520. PacketLoss: loss,
  521. Rtts: p.rtts,
  522. Addr: p.addr,
  523. IPAddr: p.ipaddr,
  524. MaxRtt: p.maxRtt,
  525. MinRtt: p.minRtt,
  526. AvgRtt: p.avgRtt,
  527. StdDevRtt: p.stdDevRtt,
  528. }
  529. return &s
  530. }
  531. func isIPv4(ip net.IP) bool {
  532. return len(ip.To4()) == net.IPv4len
  533. }
  534. var seed = time.Now().UnixNano()
  535. // getSeed returns a goroutine-safe unique seed
  536. func getSeed() int64 {
  537. return atomic.AddInt64(&seed, 1)
  538. }