@@ -96,6 +96,7 @@ const (
9696var (
9797 ipv4Proto = map [string ]string {"icmp" : "ip4:icmp" , "udp" : "udp4" }
9898 ipv6Proto = map [string ]string {"icmp" : "ip6:ipv6-icmp" , "udp" : "udp6" }
99+ globalmu sync.RWMutex
99100)
100101
101102// New returns a new PingClient struct pointer.
@@ -602,9 +603,13 @@ func (p *PingClient) processPacket(recv *packet) error {
602603func (p * PingClient ) sendICMP (conn , conn6 * icmp.PacketConn ) error {
603604 wg := new (sync.WaitGroup )
604605 for _ , addr := range p .IPs {
606+ globalmu .RLock ()
605607 if ! p .Continuous && p .PacketsSent [addr .IP .String ()] >= p .Num {
608+ globalmu .RUnlock ()
606609 continue
607610 }
611+ globalmu .RUnlock ()
612+
608613 var cn * icmp.PacketConn
609614 var typ icmp.Type
610615 if isIPv4 (addr .IP ) {
@@ -661,7 +666,9 @@ func (p *PingClient) sendICMP(conn, conn6 *icmp.PacketConn) error {
661666 }
662667 break
663668 }
669+ globalmu .Lock ()
664670 p .PacketsSent [ipStr ]++
671+ globalmu .Unlock ()
665672 wg .Done ()
666673 }(cn , dst , ipStr , msgBytes )
667674 }
@@ -681,6 +688,8 @@ func (p *PingClient) listen(netProto string) (*icmp.PacketConn, error) {
681688}
682689
683690func (p * PingClient ) initPacketsConfig () {
691+ globalmu .Lock ()
692+ defer globalmu .Unlock ()
684693 for _ , addr := range p .IPs {
685694 p .PacketsSent [addr .IP .String ()] = 0
686695 p .PacketsRecv [addr .IP .String ()] = 0
@@ -691,6 +700,8 @@ func (p *PingClient) initPacketsConfig() {
691700
692701// All checks whether all the map entry satisfies the function f
693702func All (m map [string ]int , f func (int , int ) bool , num int ) bool {
703+ globalmu .RLock ()
704+ defer globalmu .RUnlock ()
694705 for _ , val := range m {
695706 if ! f (val , num ) {
696707 return false
@@ -729,7 +740,9 @@ func (p *PingClient) Statistics() []*Statistics {
729740// StatisticsPerIP returns the statistics of the Ping info to the given IP address.
730741func (p * PingClient ) StatisticsPerIP (ipAddr * net.IPAddr ) * Statistics {
731742 var ipStr string = ipAddr .IP .String ()
743+ globalmu .RLock ()
732744 loss := float64 (p .PacketsSent [ipStr ]- p .PacketsRecv [ipStr ]) / float64 (p .PacketsSent [ipStr ]) * 100
745+ globalmu .Unlock ()
733746 var min , max , total time.Duration
734747 if len (p .rtts [ipStr ]) > 0 {
735748 min = p .rtts [ipStr ][0 ]
@@ -744,6 +757,7 @@ func (p *PingClient) StatisticsPerIP(ipAddr *net.IPAddr) *Statistics {
744757 }
745758 total += rt
746759 }
760+ globalmu .RLock ()
747761 s := Statistics {
748762 PacketsSent : p .PacketsSent [ipStr ],
749763 PacketsRecv : p .PacketsRecv [ipStr ],
@@ -755,6 +769,7 @@ func (p *PingClient) StatisticsPerIP(ipAddr *net.IPAddr) *Statistics {
755769 MaxRtt : max ,
756770 MinRtt : min ,
757771 }
772+ globalmu .RUnlock ()
758773 if len (p .rtts [ipStr ]) > 0 {
759774 s .AvgRtt = total / time .Duration (len (p .rtts [ipStr ]))
760775 var sumsquares time.Duration
0 commit comments