-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
214 lines (170 loc) · 3.72 KB
/
client.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"math"
"net"
"os"
"strings"
"time"
)
type client struct {
config *config
sigint *chan bool
conn net.Conn
ctx context.Context
cancel context.CancelFunc
ticker *time.Ticker
tickerDone chan bool
stat struct {
addr string
times []int64
sent int
received int
corrupted int
}
}
type reply struct {
err error
start int64
end int64
data []byte
len int
}
func (c *client) run() {
var err error
c.init()
dialer := &net.Dialer{
LocalAddr: c.config.addr.local,
}
c.conn, err = dialer.DialContext(c.ctx, c.config.protocol, c.config.addr.remote)
if err != nil {
printNetworkError(err, c.config.debug)
os.Exit(1)
}
defer c.conn.Close()
c.stat.addr = c.conn.RemoteAddr().String()
remoteAddr, _, _ := net.SplitHostPort(c.conn.RemoteAddr().String())
fmt.Printf("Hostname %s resolved as %s\n\n", c.config.host.remote, remoteAddr)
c.startEcho()
c.printStat()
}
func (c *client) init() {
c.ticker = time.NewTicker(c.config.echoPeriod)
c.tickerDone = make(chan bool)
c.ctx, c.cancel = context.WithTimeout(context.Background(), c.config.timeout)
go c.close()
}
func (c *client) close() {
<-*c.sigint
c.cancel()
if c.conn != nil {
c.conn.Close()
}
c.ticker.Stop()
c.tickerDone <- true
}
func (c *client) startEcho() {
counter := c.config.count
for {
select {
case <-c.tickerDone:
return
case <-c.ticker.C:
if !c.config.infinite {
if counter == 0 {
return
} else {
counter--
}
}
if c.sendEcho() {
return
}
}
}
}
func (c *client) sendEcho() bool {
c.stat.sent++
buf := make([]byte, 4096)
c.conn.SetWriteDeadline(time.Now().Add(c.config.deadline))
_, err := c.conn.Write(c.config.pattern)
if err != nil {
c.printReply(reply{err: err})
return errors.Is(err, net.ErrClosed) || isConnectionReset(err)
}
start := time.Now().UnixMilli()
c.conn.SetReadDeadline(time.Now().Add(c.config.deadline))
n, err := c.conn.Read(buf)
if err != nil {
if err == io.EOF {
c.printReply(reply{err: net.ErrClosed})
return true
}
c.printReply(reply{err: err})
return errors.Is(err, net.ErrClosed) || isConnectionReset(err)
}
end := time.Now().UnixMilli()
c.stat.received++
c.printReply(reply{
start: start,
end: end,
data: buf,
len: n,
})
return false
}
func (c *client) printReply(r reply) {
if r.err != nil {
printNetworkError(r.err, c.config.debug)
} else {
echoTime := r.end - r.start
c.stat.times = append(c.stat.times, echoTime)
status := "OK"
if !bytes.Equal(c.config.pattern, r.data[:r.len]) {
c.stat.corrupted++
status = "CORRUPT"
}
fmt.Printf("Reply from %s, time %v ms, %s\n", c.stat.addr, echoTime, status)
}
}
func (c *client) printStat() {
if c.stat.sent == 0 {
return
}
min, max, avg := c.getTimeStat()
lost := c.stat.sent - c.stat.received
loss := math.Floor(((float64(lost)*float64(100))/float64(c.stat.sent))*100) / 100
fmt.Printf("\n--- %s %s echo statistics ---\n", c.stat.addr, strings.ToUpper(c.config.protocol))
fmt.Printf("%v echo request sent, %v received, %v lost (%v%% loss), %v corrupted\n", c.stat.sent, c.stat.received, lost, loss, c.stat.corrupted)
fmt.Printf("Round-trip time min/avg/max: %v / %v / %v ms\n", min, avg, max)
}
func (c *client) getTimeStat() (int64, int64, float64) {
var min, max int64
t := c.stat.times
if len(t) == 0 {
return 0, 0, 0
}
if len(t) == 1 {
return t[0], t[0], float64(t[0])
}
if len(t) >= 2 {
min = t[0]
max = t[0]
}
var total int64
for _, v := range t {
total += v
if min > v {
min = v
}
if max < v {
max = v
}
}
avg := math.Floor((float64(total)/float64(len(t)))*100) / 100
return min, max, avg
}