- 构建 icmp 报文
package main
import (
"bytes"
"encoding/binary"
"fmt"
"net"
)
const MsgLen = 4000
type ICMP struct {
Type uint8
Code uint8
Checksum uint16
Identifier uint16
SequenceNum uint16
msgData [MsgLen]uint8
}
func CheckSum(data []byte) uint16 {
var (
sum uint32
length int = len(data)
index int
)
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() {
var (
icmp ICMP
laddr net.IPAddr = net.IPAddr{IP: net.ParseIP("192.168.1.105")}
raddr net.IPAddr = net.IPAddr{IP: net.ParseIP("192.168.1.1")}
)
conn, err := net.DialIP("ip4:icmp", &laddr, &raddr)
if err != nil {
fmt.Println(err.Error())
return
}
defer conn.Close()
icmp.Type = 8
icmp.Code = 0
icmp.Checksum = 0
icmp.Identifier = 0
icmp.SequenceNum = 0
for i := 0; i < MsgLen; i++ {
icmp.msgData[i] = uint8(i % 127)
}
var (
buffer bytes.Buffer
)
binary.Write(&buffer, binary.BigEndian, icmp)
icmp.Checksum = CheckSum(buffer.Bytes())
buffer.Reset()
binary.Write(&buffer, binary.BigEndian, icmp)
if _, err := conn.Write(buffer.Bytes()); err != nil {
fmt.Println(err.Error())
return
}
fmt.Printf("send icmp packet success!")
}
- 构建 icmpv6 报文
package main
import (
"bytes"
"encoding/binary"
"fmt"
"net"
)
const MsgLen = 4000
type ICMP struct {
Type uint8
Code uint8
Checksum uint16
Identifier uint16
SequenceNum uint16
msgData [MsgLen]uint8
}
func CheckSum(data []byte) uint16 {
var (
sum uint32
length int = len(data)
index int
)
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() {
var (
icmp ICMP
laddr net.IPAddr = net.IPAddr{IP: net.ParseIP("fe80::8a0f:1933:96fc:9906")}
raddr net.IPAddr = net.IPAddr{IP: net.ParseIP("fe80::f401:67ff:fe6e:c58a")}
)
conn, err := net.DialIP("ip6:ipv6-icmp", &laddr, &raddr)
if err != nil {
fmt.Println(err.Error())
return
}
defer conn.Close()
icmp.Type = 128
icmp.Code = 0
icmp.Checksum = 0
icmp.Identifier = 0
icmp.SequenceNum = 0
for i := 0; i < MsgLen; i++ {
icmp.msgData[i] = uint8(i % 127)
}
var (
buffer bytes.Buffer
)
binary.Write(&buffer, binary.BigEndian, icmp)
icmp.Checksum = CheckSum(buffer.Bytes())
buffer.Reset()
binary.Write(&buffer, binary.BigEndian, icmp)
if _, err := conn.Write(buffer.Bytes()); err != nil {
fmt.Println(err.Error())
return
}
fmt.Printf("send icmpv6 packet success!")
}