Skip to content

Instantly share code, notes, and snippets.

@wyyqyl
Last active August 29, 2015 14:09
Show Gist options
  • Save wyyqyl/b5e7792e73982a862809 to your computer and use it in GitHub Desktop.
Save wyyqyl/b5e7792e73982a862809 to your computer and use it in GitHub Desktop.
ping request
package main
import (
"bytes"
"encoding/binary"
"fmt"
"net"
"time"
)
type ICMP struct {
Type uint8
Code uint8
Checksum uint16
Identifier uint16
SequenceNum uint16
}
func main() {
raddr, _ := net.ResolveIPAddr("ip", "ss.lynn4.me")
fmt.Println("Target IP:", raddr.String())
conn, err := net.DialIP("ip4:icmp", nil, raddr)
if err != nil {
fmt.Println(err.Error())
return
}
defer conn.Close()
icmp := ICMP{8, 0, 0, 13, 37}
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("Write err:", err.Error())
return
}
conn.SetReadDeadline((time.Now().Add(time.Second * 3)))
response := make([]byte, 1024)
if _, err := conn.Read(response); err != nil {
fmt.Println("Read err:", err.Error())
return
}
fmt.Println(response)
}
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) + (sum & 0xffff)
sum += (sum >> 16)
return uint16(^sum)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment