/
ping.go
120 lines (105 loc) · 2.09 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
package ping
import (
"errors"
"fmt"
"net"
"os"
"sync"
"time"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
)
var (
mu sync.Mutex
queue *Queue
seq int
conn *icmp.PacketConn
pingServer *Server
ProcessId int
Debug bool
)
type PingCmd struct {
ip string
timeout int
sendTime time.Time
done chan string
key string
}
func init() {
ProcessId = os.Getpid() & 0xffff
}
func SetDevice(d string) {
var err error
conn, err = icmp.ListenPacket("ip4:icmp", "0.0.0.0")
if err != nil {
panic(err.Error())
}
queue = NewQueue()
pingServer = NewServer(d, ProcessId)
pingServer.Start()
c := make(chan IcmpEchoReply)
pingServer.ReceivingIcmp(c)
go func(c <-chan IcmpEchoReply) {
for e := range c {
k := fmt.Sprintf("%s:%d", e.srcIp, e.seq)
//log.Println(e.srcIp, ">", e.dstIp, e.seq, k)
p, ok := queue.Get(k)
if ok {
p.done <- k
}
}
}(c)
}
func Run(address string, timeout int) error {
wm, pcmd, err := createIcmp(address, timeout)
if err != nil {
return err
}
defer queue.Del(pcmd.key)
wb, err := wm.Marshal(nil)
if err != nil {
return err
}
if n, err := conn.WriteTo(wb, &net.IPAddr{IP: net.ParseIP(address)}); err != nil {
return err
} else if n != len(wb) {
return errors.New("connection write to size error")
}
select {
case <-time.After(time.Duration(timeout) * time.Millisecond):
return errors.New("ping timeout")
case <-pcmd.done:
return nil
}
}
func createIcmp(address string, timeout int) (icmp.Message, *PingCmd, error) {
mu.Lock()
defer mu.Unlock()
if seq == 65535 {
seq = 0
}
i := 0
for ; i < 3; i++ {
seq++
key := fmt.Sprintf("%s:%d", address, seq)
p := PingCmd{
ip: address,
timeout: timeout,
done: make(chan string, 1),
sendTime: time.Now(),
key: key,
}
if ok := queue.Add(key, &p); ok {
wm := icmp.Message{
Type: ipv4.ICMPTypeEcho, Code: 0,
Body: &icmp.Echo{
ID: ProcessId,
Seq: seq,
Data: []byte("fast ping it!"),
},
}
return wm, &p, nil
}
}
return icmp.Message{}, &PingCmd{}, errors.New("Ping queue full")
}