-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathping.go
57 lines (46 loc) · 1.28 KB
/
ping.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"context"
"fmt"
"runtime"
"github.com/go-ping/ping"
)
func Ping(addr string, ctx *context.Context, host *host, pingedAddr *onlineHosts) {
defer wg.Done()
pinger, err := ping.NewPinger(addr)
if runtime.GOOS == "windows" {
pinger.SetPrivileged(true)
}
if err != nil {
panic(err)
}
pinger.Count = host.Count
pinger.Timeout = host.PingTime
pinger.Interval = host.Interval
pinger.OnRecv = func(pkt *ping.Packet) {
// got reply remove from available addresses
if pingedAddr.bytes == 0 {
openAddr.delAddr(addr)
}
pingedAddr.addr = addr
pingedAddr.bytes += pkt.Nbytes
pingedAddr.time = pkt.Rtt
if debug {
fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v ttl=%v\n",
pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt, pkt.Ttl)
}
}
pinger.OnFinish = func(stats *ping.Statistics) {
if debug {
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)
fmt.Printf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n",
stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
}
}
err = pinger.Run() // Blocks until finished.
if err != nil {
fmt.Printf("Failed to ping target host: %s", err)
}
}