This repository has been archived by the owner on Apr 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
ping.go
136 lines (112 loc) · 2.3 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
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
package icmpping
import (
"bytes"
"encoding/binary"
"iochen.com/v2gen/app/ping"
"iochen.com/v2gen/infra/vmess"
"log"
"net"
"time"
)
type icmp struct {
Type uint8
Code uint8
CheckSum uint16
Identifier uint16
SequenceNum uint16
}
func getICMP() (*icmp, error) {
icmp := &icmp{Type: 8}
var buffer bytes.Buffer
if err := binary.Write(&buffer, binary.BigEndian, *icmp); err != nil {
return nil, err
}
icmp.CheckSum = checkSum(buffer.Bytes())
buffer.Reset()
return icmp, nil
}
func sendICMPRequest(icmp *icmp, ip *net.IPAddr, timeout time.Duration) (time.Duration, error) {
conn, err := net.DialIP("ip4:icmp", nil, ip)
if err != nil {
return -1, err
}
defer func() {
err = conn.Close()
if err != nil {
log.Println(err)
}
}()
var buffer bytes.Buffer
if err = binary.Write(&buffer, binary.BigEndian, icmp); err != nil {
return -1, err
}
if _, err := conn.Write(buffer.Bytes()); err != nil {
return -1, err
}
start := time.Now()
if err = conn.SetReadDeadline(time.Now().Add(time.Second * timeout)); err != nil {
return -1, err
}
recv := make([]byte, 1024)
_, err = conn.Read(recv)
if err != nil {
return -1, err
}
end := time.Now()
return end.Sub(start), nil
}
func Ping(lk *vmess.Link, count int, totalTimeout, eachTimeout time.Duration) (*ping.Status, error) {
ps := &ping.Status{
Durations: &ping.DurationList{},
}
icmp, err := getICMP()
if err != nil {
return ps, err
}
ip, err := net.ResolveIPAddr("ip", lk.Add)
if err != nil {
return ps, err
}
timeout := make(chan bool, 1)
go func() {
time.Sleep(totalTimeout * time.Second)
timeout <- true
}()
L:
for round := 0; round < count; round++ {
chDelay := make(chan time.Duration)
go func() {
delay, err := sendICMPRequest(icmp, ip, eachTimeout)
if err != nil {
ps.ErrCounter++
}
chDelay <- delay
}()
select {
case delay := <-chDelay:
if delay > 0 {
*ps.Durations = append(*ps.Durations, ping.Duration(delay))
}
case <-timeout:
break L
}
}
return ps, nil
}
func checkSum(data []byte) uint16 {
var (
sum uint32
length = len(data)
index int
)
for length > 1 {
sum += uint32(data[index])<<8 + uint32(data[index+1])
index += 2
length -= 2
}
if length > 0 {
sum += uint32(data[index])
}
sum += sum >> 16
return uint16(^sum)
}