Skip to content

Commit

Permalink
Merge pull request #145 from perhallgren/fix/stats-race
Browse files Browse the repository at this point in the history
fix/stats race
  • Loading branch information
SuperQ authored Feb 3, 2025
2 parents 50c55f1 + cb7d28f commit a13e284
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
12 changes: 12 additions & 0 deletions ping.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,8 +353,10 @@ func (p *Pinger) updateStatistics(pkt *Packet) {
func (p *Pinger) SetIPAddr(ipaddr *net.IPAddr) {
p.ipv4 = isIPv4(ipaddr.IP)

p.statsMu.Lock()
p.ipaddr = ipaddr
p.addr = ipaddr.String()
p.statsMu.Unlock()
}

// IPAddr returns the ip address of the target host.
Expand Down Expand Up @@ -407,7 +409,9 @@ func (p *Pinger) Resolve() error {

p.ipv4 = isIPv4(ipaddr.IP)

p.statsMu.Lock()
p.ipaddr = ipaddr
p.statsMu.Unlock()

return nil
}
Expand All @@ -416,10 +420,14 @@ func (p *Pinger) Resolve() error {
// DNS name like "www.google.com" or IP like "127.0.0.1".
func (p *Pinger) SetAddr(addr string) error {
oldAddr := p.addr
p.statsMu.Lock()
p.addr = addr
p.statsMu.Unlock()
err := p.Resolve()
if err != nil {
p.statsMu.Lock()
p.addr = oldAddr
p.statsMu.Unlock()
return err
}
return nil
Expand Down Expand Up @@ -852,7 +860,9 @@ func (p *Pinger) processPacket(recv *packet) error {
inPkt.Seq = pkt.Seq
// If we've already received this sequence, ignore it.
if _, inflight := p.awaitingSequences[*pktUUID][pkt.Seq]; !inflight {
p.statsMu.Lock()
p.PacketsRecvDuplicates++
p.statsMu.Unlock()
if p.OnDuplicateRecv != nil {
p.OnDuplicateRecv(inPkt)
}
Expand Down Expand Up @@ -945,7 +955,9 @@ func (p *Pinger) sendICMP(conn packetConn) error {
}
// mark this sequence as in-flight
p.awaitingSequences[currentUUID][p.sequence] = struct{}{}
p.statsMu.Lock()
p.PacketsSent++
p.statsMu.Unlock()
p.sequence++
if p.sequence > 65535 {
newUUID := uuid.New()
Expand Down
8 changes: 8 additions & 0 deletions ping_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -870,3 +870,11 @@ func TestSetResolveTimeout(t *testing.T) {
err = p.SetAddr("127.0.0.1")
AssertNoError(t, err)
}

func TestRunStatisticsConcurrent(t *testing.T) {
p := New("www.google.com")
p.Count = 1
p.Interval = time.Millisecond
go p.Statistics()
p.Run()
}

0 comments on commit a13e284

Please sign in to comment.