-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoping.go
148 lines (135 loc) · 4.32 KB
/
goping.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package main
import (
"flag"
"fmt"
"math"
"net"
"os"
"os/signal"
"time"
)
const (
minSleepBetweenPings = 10 * time.Millisecond
usage = "Usage: goping [options] <destination>"
)
var (
timeoutParam = flag.Int("W", 1, "Timeout, in seconds")
intervalParam = flag.Float64("i", 1, "Interval between pings, in seconds")
countParam = flag.Int("c", -1, "Number of pings to send")
ttlParam = flag.Int("t", 64, "TTL")
sizeParam = flag.Int("s", 56, "Payload size")
quietParam = flag.Bool("q", false, "Quiet mode")
)
func main() {
flag.Parse()
if flag.NArg() != 1 ||
*timeoutParam <= 0 ||
*intervalParam < 0 ||
*ttlParam <= 0 || *ttlParam > 255 ||
*sizeParam < 0 || *sizeParam > MaxPacketSize-MinPacketSize {
fmt.Println(usage)
flag.PrintDefaults()
os.Exit(-1)
}
destinationParam := flag.Arg(0)
destinationAddress, err := net.ResolveIPAddr("ip", destinationParam)
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Failed to resolve destinationParam %s. Error: %v", destinationParam, err)
os.Exit(-2)
}
interval := time.Duration(float64(time.Second) * (*intervalParam))
interruptChannel := make(chan os.Signal, 1)
signal.Notify(interruptChannel, os.Interrupt)
fmt.Printf("PING %v (%v) %v data bytes\n", destinationParam, destinationAddress.IP, *sizeParam)
if err := ping(interruptChannel, destinationAddress.IP, *sizeParam, *countParam, *ttlParam, *timeoutParam,
interval, *quietParam); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Ping failed. %v", err)
os.Exit(-3)
}
}
func ping(interruptChannel chan os.Signal, destinationIp net.IP, payloadLen, count, ttl, timeoutSec int,
interval time.Duration, quiet bool) (err error) {
pinger := NewPinger(destinationIp, payloadLen)
if err := pinger.Init(uint8(ttl), time.Duration(timeoutSec)*time.Second); err != nil {
return fmt.Errorf("initialization error %v", err)
}
var stats pingStats
startTime := time.Now()
pinger.StartReceiver()
pingLoop:
for i := 0; count < 0 || i < count; i++ {
if err := pinger.Send(uint16(i) + 1); err != nil {
return fmt.Errorf("failed to send ping: %v", err)
}
sendTime := time.Now()
nextSendTime := sendTime.Add(interval)
stats.sent()
receivedResponse := false
for {
pinger.seqChan <- uint16(i) + 1
select {
case <-interruptChannel:
break pingLoop //Interrupted, stop pinging
case received := <-pinger.resultChan: //received something!
if received.err != nil {
if received.err == ErrUnexpectedPacket || received.err == ErrTimeout {
break //break select
}
return fmt.Errorf("error reading from socket: %v", err)
}
rtt := received.recvTime.Sub(sendTime)
stats.received(rtt)
receivedResponse = true
if quiet {
break
}
fmt.Printf("%d bytes from %s: icmp_seq=%d ttl=%d time=%.1f ms\n",
received.len, received.source, received.seq, received.ttl, float64(rtt.Microseconds())/1000,
)
}
if receivedResponse || interval == 0 || time.Now().After(nextSendTime) {
break
}
}
if sleepToNextInterval := nextSendTime.Sub(time.Now()); sleepToNextInterval >= minSleepBetweenPings {
select {
case <-interruptChannel:
break pingLoop
case <-time.After(sleepToNextInterval):
continue pingLoop
}
}
}
close(pinger.seqChan)
fmt.Printf("---- %v ping statistics ---\n%v", destinationIp, stats.stats(time.Now().Sub(startTime)))
return nil
}
type pingStats struct {
nsent, nreceived int
rttMin, rttMax, rttSum, rttSumSq float64
}
func (ps *pingStats) received(rtt time.Duration) {
rttMillis := float64(rtt.Microseconds()) / 1000
if ps.nreceived == 0 || ps.rttMax < rttMillis {
ps.rttMax = rttMillis
}
if ps.nreceived == 0 || ps.rttMin > rttMillis {
ps.rttMin = rttMillis
}
ps.nreceived++
ps.rttSum += rttMillis
ps.rttSumSq += rttMillis * rttMillis
}
func (ps *pingStats) sent() {
ps.nsent++
}
func (ps *pingStats) stats(totalTime time.Duration) string {
nreceived := float64(ps.nreceived)
packetLoss := 100.0 * (ps.nsent - ps.nreceived) / ps.nsent
rttAvg := ps.rttSum / nreceived
rttStdDev := math.Sqrt(ps.rttSumSq/nreceived - (ps.rttSum/nreceived)*(ps.rttSum/nreceived))
return fmt.Sprintf("%v packets transmitted, %v received, %v%% packet loss, time %vms\n"+
"rtt min/avg/max/mdev = %.3f/%.3f/%.3f/%.3f ms\n",
ps.nsent, ps.nreceived, packetLoss, totalTime.Milliseconds(), ps.rttMin, rttAvg, ps.rttMax, rttStdDev,
)
}