go-ping / ping

ICMP Ping library for Go
MIT License
1.31k stars 344 forks source link

ping result is always same for different addresses #198

Closed SHA65536 closed 2 years ago

SHA65536 commented 2 years ago

Hello! I tried making a program that will ping a list of IPs and gather results.

func scrapeAll() {
    pinger := ping.New("0.0.0.0")
    // Tried this too
    // pinger, _ := ping.NewPinger("0.0.0.0")
    pinger.Count = 5
    pinger.Size = 24
    pinger.Interval = time.Second
    pinger.Timeout = time.Second * 3
    pinger.TTL = 64
    pinger.SetPrivileged(true)
    pinger.OnFinish = handlePing
    uids, hosts := getEnabledDevices()
    for i := range uids {
        pinger.SetAddr(hosts[i])
        err := pinger.Run()
        if err != nil {
            consoleLog.Printf("Failed to ping target host %s, %v",hosts[i], err)
            continue
        }
    }
}
func handlePing(stats *ping.Statistics) {
    consoleLog.Printf("%v - %v", stats.Addr, stats.AvgRtt)
}

When running I get the result:

2022/01/10 11:20:10 127.0.0.1 - 197.967µs
2022/01/10 11:20:10 8.8.8.8 - 197.967µs
2022/01/10 11:20:10 192.168.5.7 - 197.967µs 

Tested multiple times so it's not a coincidence. Maybe is there some internal variable in the pinger I need to reset before each ping? Cheers.

go version go1.17.6 windows/amd64

SHA65536 commented 2 years ago

It seems that in runLoop you check packets p.PacketsRecv >= p.Count and p.PacketsSent >= p.Count So when changing the address using SetAddr the p.PacketsRecv and p.PacketsSent and other stats are not getting reset.

CHTJonas commented 2 years ago

Please don't do that. ping.Pinger instances aren't designed to be used to ping multiple targets in that way.

Initialise a new Pinger for each host inside the for loop.