-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathping.go
More file actions
275 lines (243 loc) · 6.26 KB
/
ping.go
File metadata and controls
275 lines (243 loc) · 6.26 KB
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package main
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"math"
"net"
"os"
// "runtime"
"sync"
//"testing"
"time"
"./xnet/xnternal/iana" //use of internal package not allowed
"./xnet/xnternal/nettest"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
//-ldflags=-linkmode=internal
func main() {
//使用go get 安装x/net 不能成功
// planB: git clone git@github.com:golang/net.git $GOPATH./src/golang.org/x/net/
//这是golang net test 代码用来学习 删除ip6 的支持数据
if m, ok := nettest.SupportsRawIPSocket(); !ok {
fmt.Println(m)
return
} else {
//fmt.Println(m, ok)
}
var wg sync.WaitGroup
wg.Add(5)
for i := 0; i < 1; i++ {
go func(i int) {
defer wg.Done()
time.Sleep(time.Duration(i) * time.Second)
for i2, tt := range privilegedPingTests {
//fmt.Println(i, tt)
if err := doPing(tt, i2); err != nil {
fmt.Println(err)
return
}
}
}(i)
}
wg.Wait()
}
func googleAddr(c *icmp.PacketConn, protocol int) (net.Addr, error) {
const host = "www.baidu.com"
ips, err := net.LookupIP(host)
if err != nil {
return nil, err
}
//fmt.Println(ips)
netaddr := func(ip net.IP) (net.Addr, error) {
switch c.LocalAddr().(type) {
case *net.UDPAddr:
return &net.UDPAddr{IP: ip}, nil
case *net.IPAddr:
return &net.IPAddr{IP: ip}, nil
default:
return nil, errors.New("neither UDPAddr nor IPAddr")
}
}
for _, ip := range ips {
switch protocol {
case iana.ProtocolICMP:
//fmt.Println("ICMP")
//fmt.Println(ip.To4())
//os.Exit(1)
if ip.To4() != nil {
return netaddr(ip)
}
case iana.ProtocolIPv6ICMP:
if ip.To16() != nil && ip.To4() == nil {
return netaddr(ip)
}
}
}
return nil, errors.New("no A or AAAA record")
}
type pingTest struct {
network, address string
protocol int //协议
mtype icmp.Type //协议类型
}
var privilegedPingTests = []pingTest{
{"ip4:icmp", "0.0.0.0", iana.ProtocolICMP, ipv4.ICMPTypeEcho},
//{"ip6:ipv6-icmp", "::", iana.ProtocolIPv6ICMP, ipv6.ICMPTypeEchoRequest},
}
func Round(f float64, n int) float64 {
n10 := math.Pow10(n)
return math.Trunc((f+0.5/n10)*n10) / n10
}
func doPing(tt pingTest, seq int) error {
//net.ListenPacket(network, address)
c, err := icmp.ListenPacket(tt.network, tt.address)
if err != nil {
return err
}
defer c.Close()
dst, err := googleAddr(c, tt.protocol)
if err != nil {
return err
}
//fmt.Println(dst)
// if tt.network != "udp6" && tt.protocol == iana.ProtocolIPv6ICMP {
// var f ipv6.ICMPFilter
// f.SetAll(true)
// f.Accept(ipv6.ICMPTypeDestinationUnreachable)
// f.Accept(ipv6.ICMPTypePacketTooBig)
// f.Accept(ipv6.ICMPTypeTimeExceeded)
// f.Accept(ipv6.ICMPTypeParameterProblem)
// f.Accept(ipv6.ICMPTypeEchoReply)
// if err := c.IPv6PacketConn().SetICMPFilter(&f); err != nil {
// return err
// }
// }
now := time.Now()
ns := now.UnixNano()
nsb := bytes.NewBuffer([]byte{})
binary.Write(nsb, binary.BigEndian, ns)
//fmt.Println(ns, nsb.Bytes())
wm := icmp.Message{
Type: tt.mtype, Code: 0,
Body: &icmp.Echo{
ID: os.Getpid() & 0xffff, Seq: 1 << uint(seq),
Data: nsb.Bytes(),
},
}
//返回校验和消息
wb, err := wm.Marshal(nil)
if err != nil {
return err
}
fmt.Printf("%v", c)
//fmt.Println(wm.Body)
if n, err := c.WriteTo(wb, dst); err != nil {
return err
} else if n != len(wb) {
return fmt.Errorf("got %v; want %v", n, len(wb))
}
rb := make([]byte, 1500)
if err := c.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil {
return err
}
n, peer, err := c.ReadFrom(rb)
if err != nil {
return err
}
fmt.Println(rb)
rm, err := icmp.ParseMessage(tt.protocol, rb[:n])
if err != nil {
return err
}
//fmt.Printf("read from %v\n", peer)
//获取我们发送出去的数据 在这里可以写入时间来计算往返时间
dd, err := rm.Body.Marshal(iana.ProtocolICMP)
var timens int64
recvdata := dd[4:]
recvnsb := bytes.NewBuffer(recvdata)
binary.Read(recvnsb, binary.BigEndian, &timens)
//fmt.Println(timens)
nowc := time.Now()
ctime := nowc.UnixNano()
var cc float64
cc = float64(ctime-timens) / float64(1e6)
fmt.Printf("ping %v times:%v ms\n", peer, Round(cc, 2))
//fmt.Println(icmp.Echo(rm.Body))
//fmt.Printf("%s\n", dd[4:])
/**
* 或者使用unsafe 转换
* t := T {
A: 10,
B: "abc",
}
l := unsafe.Sizeof(t)
pb := (*[1024]byte)(unsafe.Pointer(&t))
fmt.Println("Struct:", t)
fmt.Println("Bytes:", (*pb)[:l])
*
*
*
*/
switch rm.Type {
case ipv4.ICMPTypeEchoReply, ipv6.ICMPTypeEchoReply:
return nil
default:
return fmt.Errorf("got %+v from %v; want echo reply", rm, peer)
}
}
// func TestConcurrentNonPrivilegedListenPacket(t *testing.T) {
// if testing.Short() {
// t.Skip("avoid external network")
// }
// switch runtime.GOOS {
// case "darwin":
// case "linux":
// t.Log("you may need to adjust the net.ipv4.ping_group_range kernel state")
// default:
// t.Skipf("not supported on %s", runtime.GOOS)
// }
// network, address := "udp4", "127.0.0.1"
// if !nettest.SupportsIPv4() {
// network, address = "udp6", "::1"
// }
// const N = 1000
// var wg sync.WaitGroup
// wg.Add(N)
// for i := 0; i < N; i++ {
// go func() {
// defer wg.Done()
// c, err := icmp.ListenPacket(network, address)
// if err != nil {
// t.Error(err)
// return
// }
// c.Close()
// }()
// }
// wg.Wait()
// }
// var nonPrivilegedPingTests = []pingTest{
// {"udp4", "0.0.0.0", iana.ProtocolICMP, ipv4.ICMPTypeEcho},
// {"udp6", "::", iana.ProtocolIPv6ICMP, ipv6.ICMPTypeEchoRequest},
// }
// func TestNonPrivilegedPing(t *testing.T) {
// if testing.Short() {
// t.Skip("avoid external network")
// }
// switch runtime.GOOS {
// case "darwin":
// case "linux":
// t.Log("you may need to adjust the net.ipv4.ping_group_range kernel state")
// default:
// t.Skipf("not supported on %s", runtime.GOOS)
// }
// for i, tt := range nonPrivilegedPingTests {
// if err := doPing(tt, i); err != nil {
// t.Error(err)
// }
// }
// }