-
Notifications
You must be signed in to change notification settings - Fork 0
/
ping.go
72 lines (68 loc) · 1.21 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
package ping
import (
"errors"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
"math/rand"
"net"
"os"
"time"
)
const (
ProtocolICMP = 1
)
var (
ErrNotReply = errors.New("not echo reply")
)
func doPing(host string) (err error) {
c, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0")
if err != nil {
return
}
defer c.Close()
dst, err := net.ResolveIPAddr("ip4", host)
if err != nil {
return
}
r := rand.New(rand.NewSource(time.Now().Unix()))
wm := icmp.Message{
Type: ipv4.ICMPTypeEcho,
Body: &icmp.Echo{
ID: os.Getpid() & 0xffff, //why &0xffff ??
Seq: r.Int(),
Data: []byte("R-U-OK"),
},
}
wb, err := wm.Marshal(nil)
if err != nil {
return
}
var n int
if n, err = c.WriteTo(wb, dst); err != nil {
return
} else if n != len(wb) {
return
}
rb := make([]byte, 1500)
if err = c.SetReadDeadline(time.Now().Add(time.Second * 3)); err != nil {
return
}
n, _, err = c.ReadFrom(rb)
if err != nil {
return
}
rm, err := icmp.ParseMessage(ProtocolICMP, rb[:n])
if err != nil {
return
}
if rm.Type != ipv4.ICMPTypeEchoReply {
return ErrNotReply
}
return nil
}
func DoPing(host string) error {
return doPing(host)
}
func Ping(host string) bool {
return doPing(host) == nil
}