6
6
--]]
7
7
8
8
local socket = require ' eco.socket'
9
+ local packet = require ' eco.packet'
9
10
local time = require ' eco.time'
10
11
11
- local ICMP_HEADER_LEN = 8
12
-
13
12
local dest_ip = ' 127.0.0.1'
14
13
local local_id = math.random (0 , 65535 )
15
- local local_seq = 1
16
14
local local_data = ' hello'
17
-
18
- local function build_icmp_req ()
19
- local data = {
20
- string.char (socket .ICMP_ECHO ), -- type
21
- ' \0 ' , -- code
22
- ' \0\0 ' , -- checksum
23
- ' \0\0 ' , -- id: the kernel will assign it with local port
24
- string.char (local_seq >> 8 , local_seq & 0xff ), -- sequence
25
- local_data
26
- }
27
-
28
- local_seq = local_seq + 1
29
-
30
- return table.concat (data )
31
- end
32
-
33
- local function parse_icmp_resp (data )
34
- if # data < ICMP_HEADER_LEN then
35
- return nil , ' invalid icmp resp'
36
- end
37
-
38
- local icmp_type = data :byte (1 )
39
- local id_hi = data :byte (5 )
40
- local id_lo = data :byte (6 )
41
- local id = (id_hi << 8 ) + id_lo
42
-
43
- local seq_hi = data :byte (7 )
44
- local seq_lo = data :byte (8 )
45
- local seq = (seq_hi << 8 ) + seq_lo
46
-
47
- return icmp_type , id , seq , # data - ICMP_HEADER_LEN
48
- end
15
+ local local_seq = 1
49
16
50
17
local s , err = socket .icmp ()
51
18
if not s then
@@ -60,34 +27,32 @@ s:bind(nil, local_id)
60
27
print (string.format (' PING %s, %d bytes of data.' , dest_ip , # local_data ))
61
28
62
29
while true do
63
- local _ , err = s :sendto (build_icmp_req (), dest_ip , 0 )
30
+ local pkt = packet .icmp (socket .ICMP_ECHO , 0 , 0 , local_seq , ' hello' )
31
+ local_seq = local_seq + 1
32
+
33
+ local _ , err = s :sendto (pkt , dest_ip , 0 )
64
34
if err then
65
35
print (' send fail:' , err )
66
36
break
67
37
end
68
38
69
39
local start = time .now ()
70
40
71
- local resp , peer = s :recvfrom (1024 , 5.0 )
72
- if not resp then
41
+ local data , peer = s :recvfrom (1024 , 5.0 )
42
+ if not data then
73
43
print (' recv fail:' , peer )
74
44
break
75
45
end
76
46
77
- local elapsed = time .now () - start
78
-
79
- local icmp_type , id , seq , n = parse_icmp_resp (resp )
47
+ pkt = packet .from_icmp (data )
80
48
81
- if icmp_type then
82
- if icmp_type == socket .ICMP_ECHOREPLY then
83
- if id == local_id then
84
- print (string.format (' %d bytes from %s: icmp_seq=%d time=%.3f ms' , n , peer .ipaddr , seq , elapsed * 1000 ))
85
- end
86
- else
87
- print (' Got ICMP packet with type ' .. icmp_type )
49
+ if pkt .type == socket .ICMP_ECHOREPLY then
50
+ if pkt .id == local_id then
51
+ local elapsed = time .now () - start
52
+ print (string.format (' %d bytes from %s: icmp_seq=%d time=%.3f ms' , # pkt .data , peer .ipaddr , pkt .sequence , elapsed * 1000 ))
88
53
end
89
54
else
90
- print (id )
55
+ print (' Got ICMP packet with type ' .. pkt . type )
91
56
end
92
57
93
58
time .sleep (1.0 )
0 commit comments