I'm trying to ping various hosts at the same time using github.com/sparrc/go-ping and goroutines. The issue is that it seems "stats" is shared between all the goroutines. That means "stats" has approximately the same value in all goroutines. For me they should be a instance of "stats" for every goroutine. What also puzzles me is that even for an unexisting host there are values in stats. I was thinking may be it's not possible to ping multiple hosts using ICMP from a socket but obviously I'm able to perform such a thing from PowerShell.
Here is my code:
package main
import (
"fmt"
"sync"
"github.com/sparrc/go-ping"
)
var wg sync.WaitGroup
func pingfunc(ip string) {
defer wg.Done()
pinger, err := ping.NewPinger(ip)
pinger.SetPrivileged(true)
if err != nil {
panic(err)
}
pinger.Count = 3
pinger.OnFinish = func(stats *ping.Statistics) {
fmt.Println(stats)
}
pinger.Run() // blocks until finished
}
func main() {
ips := [4]string{"172.26.236.3",
"172.26.236.5",
"172.26.236.10",
"172.26.2.20"} //this host doesn't exist
for _, s := range ips {
wg.Add(1)
go pingfunc(s)
}
wg.Wait()
}
Output:
&{3 2 -50 172.26.236.3 172.26.236.3 [12.9656ms 12.9656ms 11.9679ms] 11.9679ms 12.9656ms 12.633033ms 470.32µs}
&{3 2 -50 172.26.236.10 172.26.236.10 [12.9656ms 12.9656ms 11.9679ms] 11.9679ms 12.9656ms 12.633033ms 470.32µs}
&{3 3 0 172.26.2.20 172.26.2.20 [12.9656ms 14.9603ms 17.166ms] 12.9656ms 17.166ms 15.030633ms 1.715527ms}
&{3 3 0 172.26.236.5 172.26.236.5 [12.9656ms 14.9603ms 17.166ms] 12.9656ms 17.166ms 15.030633ms 1.715527ms}1.850632ms}