diff --git a/ping.go b/ping.go index 452f558..7eb6a43 100644 --- a/ping.go +++ b/ping.go @@ -590,7 +590,12 @@ func (p *Pinger) Statistics() *Statistics { p.statsMu.RLock() defer p.statsMu.RUnlock() sent := p.PacketsSent - loss := float64(sent-p.PacketsRecv) / float64(sent) * 100 + + var loss float64 + if sent > 0 { + loss = float64(sent-p.PacketsRecv) / float64(sent) * 100 + } + s := Statistics{ PacketsSent: sent, PacketsRecv: p.PacketsRecv, diff --git a/ping_test.go b/ping_test.go index ddad7f3..95ab3e1 100644 --- a/ping_test.go +++ b/ping_test.go @@ -477,6 +477,22 @@ func TestStatisticsLossy(t *testing.T) { } } +func TestStatisticsZeroDivision(t *testing.T) { + p := New("localhost") + err := p.Resolve() + AssertNoError(t, err) + AssertEqualStrings(t, "localhost", p.Addr()) + + p.PacketsSent = 0 + stats := p.Statistics() + + // If packets were not sent (due to send errors), ensure that + // PacketLoss is 0 instead of NaN due to zero division + if stats.PacketLoss != 0 { + t.Errorf("Expected %v, got %v", 0, stats.PacketLoss) + } +} + // Test helpers func makeTestPinger() *Pinger { pinger := New("127.0.0.1")