forked from Mrs4s/MiraiGo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcping.go
55 lines (49 loc) · 954 Bytes
/
tcping.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
package utils
import (
"net"
"time"
)
type ICMPPingResult struct {
PacketsSent int
PacketsLoss int
AvgTimeMill int64
}
// RunTCPPingLoop 使用 tcp 进行 ping
func RunTCPPingLoop(ipport string, count int) (r ICMPPingResult) {
r = ICMPPingResult{
PacketsSent: count,
PacketsLoss: count,
AvgTimeMill: 9999,
}
if count <= 0 {
return
}
durs := make([]int64, 0, count)
for i := 0; i < count; i++ {
d, err := tcping(ipport)
if err == nil {
r.PacketsLoss--
durs = append(durs, d)
}
time.Sleep(time.Millisecond * 100)
}
if len(durs) > 0 {
r.AvgTimeMill = 0
for _, d := range durs {
r.AvgTimeMill += d
}
if len(durs) > 1 {
r.AvgTimeMill /= int64(len(durs))
}
}
return
}
func tcping(ipport string) (int64, error) {
t := time.Now().UnixMilli()
conn, err := net.DialTimeout("tcp", ipport, time.Second*10)
if err != nil {
return 9999, err
}
_ = conn.Close()
return time.Now().UnixMilli() - t, nil
}