-
Notifications
You must be signed in to change notification settings - Fork 5
/
udp2icmp.go
92 lines (81 loc) · 1.82 KB
/
udp2icmp.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
package libping
import (
"github.com/pkg/errors"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
"golang.org/x/sys/unix"
"net"
"os"
)
type wrappedClientPacketConn struct {
net.PacketConn
seq int
v6 bool
}
func (w wrappedClientPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
n, addr, err = w.PacketConn.ReadFrom(p)
if err != nil {
return
}
var proto int
if !w.v6 {
proto = 1
} else {
proto = 58
}
message, err := icmp.ParseMessage(proto, p)
if err != nil {
return 0, nil, errors.WithMessage(err, "parse icmp message")
}
echo, ok := message.Body.(*icmp.Echo)
if !ok {
err = errors.New("not echo message")
}
p = echo.Data
n = len(p)
return
}
func (w wrappedClientPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
w.seq++
msg := icmp.Message{
Body: &icmp.Echo{
ID: 0xDBB,
Seq: w.seq,
Data: p,
},
}
if !w.v6 {
msg.Type = ipv4.ICMPTypeEcho
} else {
msg.Type = ipv6.ICMPTypeEchoRequest
}
p, err = msg.Marshal(nil)
if err != nil {
return 0, errors.WithMessage(err, "create icmp message")
}
return w.PacketConn.WriteTo(p, addr)
}
func DialEcho(addr net.UDPAddr) (net.PacketConn, error) {
v6 := addr.IP.To4() == nil
var fd int
var err error
if !v6 {
fd, err = unix.Socket(unix.AF_INET, unix.SOCK_DGRAM, unix.IPPROTO_ICMP)
} else {
fd, err = unix.Socket(unix.AF_INET6, unix.SOCK_DGRAM, unix.IPPROTO_ICMPV6)
}
if err != nil {
return nil, errors.WithMessage(err, "create icmp socket")
}
f := os.NewFile(uintptr(fd), "dgram")
conn, err := net.FilePacketConn(f)
// closing f does not affect conn & vice versa
// pkg.go.dev/net#FilePacketConn
// github.com/golang/net/blob/765c7e89b3/icmp/listen_posix.go#L90
f.Close()
if err != nil {
return nil, errors.WithMessage(err, "create icmp packet conn")
}
return conn, nil
}