1919package lmap
2020
2121import (
22- "encoding/binary"
23- "golang.org/x/net/icmp"
2422 "log"
2523 "net"
2624 "time"
25+
26+ "golang.org/x/net/icmp"
27+ "golang.org/x/net/ipv4"
2728)
2829
2930func Ping (ip net.IP ) bool {
30- recvBuf := make ([]byte , 8 )
31+ msg := icmp.Message {
32+ Type : ipv4 .ICMPTypeEcho ,
33+ Code : 0 ,
34+ Body : & icmp.RawBody {
35+ Data : ip ,
36+ },
37+ }
38+
39+ sendBytes , err := msg .Marshal (nil )
40+ if err != nil {
41+ log .Println ("marshal icmp message" , err )
42+ }
3143
3244 // Start listening for icmp replies
3345 conn , err := icmp .ListenPacket ("ip4:icmp" , "0.0.0.0" )
@@ -38,10 +50,6 @@ func Ping(ip net.IP) bool {
3850 }
3951 defer conn .Close ()
4052
41- sendBytes := []byte {8 , 0 , 247 , 255 , 0 , 0 , 0 , 0 }
42- //expectCheckSum := int(checkSum([]byte{0, 0, 0, 0, 0, 0, 0, 0}))
43- expectCheckSum := 65535
44-
4553 _ , err = conn .WriteTo (sendBytes , & net.IPAddr {
4654 IP : ip ,
4755 })
@@ -50,42 +58,15 @@ func Ping(ip net.IP) bool {
5058 }
5159 _ = conn .SetReadDeadline (time .Now ().Add (time .Second * 2 ))
5260
53- _ , _ , err = conn .ReadFrom (recvBuf )
54- if err != nil {
55- return false
56- }
57-
58- recvType := recvBuf [0 ]
59- recvCheckSum := int (binary .BigEndian .Uint16 (recvBuf [2 :4 ]))
60-
61- _ = conn .SetReadDeadline (time.Time {})
61+ for {
62+ recvBuf := make ([]byte , 20 )
63+ _ , addr , err := conn .ReadFrom (recvBuf )
64+ if err != nil {
65+ return false
66+ }
6267
63- if recvType != 0 {
64- return false
68+ if addr .String () == ip .String () {
69+ return true
70+ }
6571 }
66-
67- if recvCheckSum != expectCheckSum {
68- return false
69- }
70-
71- return true
7272}
73-
74- //func checkSum(data []byte) uint16 {
75- // var (
76- // sum uint32
77- // length = len(data)
78- // index int
79- // )
80- // for length > 1 {
81- // sum += uint32(data[index])<<8 + uint32(data[index+1])
82- // index += 2
83- // length -= 2
84- // }
85- // if length > 0 {
86- // sum += uint32(data[index])
87- // }
88- // sum += sum >> 16
89- //
90- // return uint16(^sum)
91- //}
0 commit comments