How to ping muliple hosts at the same time

Viewed 973

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}
1 Answers

Do see this example

In your example, you have the OnFinish callback. But you would there's another callback available i.e., OnRecv.

If it receives a response, it calls the "OnRecv" callback. When it's finished, it calls the "Finish" callback.

So, for the non-existing host, as the GoDoc says:

  1. Statistics represent the stats of a currently running or finished pinger operation.
  2. Packet represents a received and processed ICMP echo packet.

You need to pick the stats from Packet struct as shown in the example for the ICMP echo packets received. So, follow the example; you'd be good to go!

Related