```go
package main
import (
"bytes"
"encoding/binary"
"fmt"
"net"
"os"
"time"
)
type ICMP struct {
Type uint8
Code uint8
Checksum uint16
Identifier uint16
SequenceNum uint16
}
func CheckSum(data []byte) uint16 {
var (
sum uint32 = 0
length int = len(data)
index int = 0
)
for length > 1 {
sum += uint32(data[index])<<8 + uint32(data[index+1])
index += 2
length -= 2
}
//if length > 0 {
// sum += uint32(data[index])
//}
sum += (sum >> 16)
return uint16(^sum)
}
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage: ", os.Args[0], "host")
os.Exit(1)
}
service := os.Args[1]
conn, err := net.Dial("ip4:icmp", service)
checkError(err)
var icmp ICMP
icmp.Type = 8 //8->echo message 0->reply message
icmp.Code = 0
icmp.Checksum = 0
icmp.Identifier = 0x8888
icmp.SequenceNum = 0xB88B
var buffer bytes.Buffer
binary.Write(&buffer, binary.BigEndian, icmp) //
icmp.Checksum = CheckSum(buffer.Bytes())
fmt.Println(buffer)
buffer.Reset()
binary.Write(&buffer, binary.BigEndian, icmp)
fmt.Println(buffer)
_, err = conn.Write(buffer.Bytes())
checkError(err)
msg := make([]byte, 1024) //var msg [512]byte
conn.SetReadDeadline(time.Now().Add(time.Second * 6))
_, err = conn.Read(msg)
checkError(err)
fmt.Println("Got response")
fmt.Println("TTL = ", msg[8])
os.Exit(0)
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}
```
有疑问加站长微信联系(非本文作者)