-
Notifications
You must be signed in to change notification settings - Fork 0
/
pinger_tcp.go
88 lines (73 loc) · 2 KB
/
pinger_tcp.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
//go:build !windows
package main
// inspired from https://github.com/cloverstd/tcping/blob/master/ping/tcp/tcp.go
import (
"context"
"fmt"
"net"
"strings"
"time"
tcpshaker "github.com/tevino/tcp-shaker"
)
type TCPPingWrapper struct {
host string
ip *net.IPAddr
hstring string
port int
str_tgt string
stats *PWStats
stopCheckLoop bool
loopTicker *time.Ticker
}
func (w *TCPPingWrapper) Start() {
w.hstring = fmt.Sprintf("tcp://%v:%v (%v:%v)", w.host, w.port, w.ip.String(), w.port)
w.stats.hrepr = fmt.Sprintf("tcp://%v:%v", w.host, w.port)
w.stats.iprepr = w.ip.IP.String()
if strings.Contains(w.stats.iprepr, ":") {
w.str_tgt = fmt.Sprintf("[%v]:%v", w.ip.String(), w.port)
w.hstring = fmt.Sprintf("tcp://%v:%v ([%v]:%v)", w.host, w.port, w.ip.String(), w.port)
} else {
w.str_tgt = fmt.Sprintf("%v:%v", w.ip.String(), w.port)
}
w.stopCheckLoop = false
w.loopTicker = time.NewTicker(time.Second)
go func(w *TCPPingWrapper) {
for !w.stopCheckLoop {
go func(t *TCPPingWrapper) {
t.spawnChecker()
}(w)
<-w.loopTicker.C
}
}(w)
}
func (w *TCPPingWrapper) spawnChecker() {
checker := tcpshaker.NewChecker()
ctx, stopChecker := context.WithCancel(context.Background())
defer stopChecker()
go func() {
if err := checker.CheckingLoop(ctx); err != nil {
fmt.Println("checking loop stopped due to fatal error: ", err)
}
}()
<-checker.WaitReady()
start := time.Now()
w.stats.lastsent = time.Now().UnixNano()
err := checker.CheckAddr(w.str_tgt, time.Second)
if err == nil {
w.stats.has_ever_received = true
w.stats.lastrecv = time.Now().UnixNano()
w.stats.lastrtt = time.Since(start)
w.stats.lastrtt_as_string = round(w.stats.lastrtt, 2).String()
}
}
func (w *TCPPingWrapper) Stop() {
w.stopCheckLoop = true
w.loopTicker.Stop()
}
func (w *TCPPingWrapper) Host() string {
return w.hstring
}
func (w *TCPPingWrapper) CalcStats(timeout_threshold int64) PWStats {
w.stats.ComputeState(timeout_threshold)
return *w.stats
}