To emulate a traditional UNIX ping command with real-time output, assign functions to the following callback fields on the Pinger instance:
OnRecv: Called when an Echo Reply is received.OnDuplicateRecv: Called when a packet with a sequence number that has already been received arrives.OnFinish: Called when the ping session completes, receiving a *probing.Statistics object.
pinger, err := probing.NewPinger("www.google.com")
if err != nil {
panic(err)
}
pinger.OnRecv = func(pkt *probing.Packet) {
fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v\n",
pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
}
pinger.OnDuplicateRecv = func(pkt *probing.Packet) {
fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v ttl=%v (DUP!)\n",
pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt, pkt.TTL)
}
pinger.OnFinish = func(stats *probing.Statistics) {
fmt.Printf("\n--- %s ping statistics ---\n", stats.Addr)
fmt.Printf("%d packets transmitted, %d packets received, %v%% packet loss\n",
stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
}
err = pinger.Run()