1 Star 0 Fork 0

彭威 / /ping

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main.go 2.29 KB
一键复制 编辑 原始数据 按行查看 历史
彭威 提交于 2022-12-09 22:44 . 1111
package main
import (
"bytes"
"encoding/binary"
"flag"
"fmt"
"net"
"os"
"time"
)
var (
timeout int64
size int
count int
host string
icmp_type uint8 = 8
icmp_code uint8 = 0
)
type Icmp struct {
Type uint8 //类型 固定8
Code uint8 //代码 固定0
CheckSum uint16 //校验和
Id uint16 //唯一标识
Sequnce uint16 //序列号
}
func main() {
getCommandArgs()
for count > 0 {
t1 := time.Now()
conn, e := net.DialTimeout("ip:icmp", host, time.Duration(timeout)*time.Millisecond)
if e != nil {
panic(e)
}
defer conn.Close()
icmp := Icmp{
Type: icmp_type,
Code: icmp_code,
CheckSum: 0,
Id: 1,
Sequnce: 1,
}
//var buf bytes.Buffer
var buf bytes.Buffer
//将icmp写入buf
binary.Write(&buf, binary.BigEndian, icmp) //大端写入:先写低位(左边是高位 右边是低位)
//定义需要发送的数据
data := make([]byte, size)
buf.Write(data)
data = buf.Bytes()
//将整个数据包进行签名
sum := checkSum(data)
data[2] = byte(sum >> 8) //checksum的高位值
data[3] = byte(sum) //checksum的低位值
conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Millisecond))
conn.Write(data)
response := make([]byte, 1000)
n, _ := conn.Read(response)
byteCount := n - 28 //字节数
ttl := response[8]
remoteIp := conn.RemoteAddr()
fmt.Printf("Reply from %s: bytes=%d time=%dms TTL=%d\n", remoteIp, byteCount, time.Since(t1).Milliseconds(), ttl)
time.Sleep(time.Duration(1000) * time.Millisecond)
count--
}
}
//计算签名
func checkSum(data []byte) uint16 {
//计算相邻的两个数相加
index := 0
var sum uint32
lenght := len(data)
for lenght > 1 {
sum += uint32(data[index])<<8 + uint32(data[index+1])
lenght -= 2
index += 2
}
if lenght != 0 {
sum += uint32(data[index])
}
//获取sum的高16位
high16 := sum >> 16
for high16 != 0 {
sum += high16 + uint32(uint16(sum))
high16 = sum >> 16
}
return uint16(^sum)
}
//获取命令行参数
func getCommandArgs() {
flag.Int64Var(&timeout, "w", 1000, "超时时长")
flag.IntVar(&size, "l", 32, "发送数据大小")
flag.IntVar(&count, "n", 4, "发送请求的次数")
flag.Parse()
args := os.Args
if len(args) == 0 {
panic("参数错误")
}
host = args[len(args)-1]
}
Go
1
https://gitee.com/PengWei0422/ping.git
git@gitee.com:PengWei0422/ping.git
PengWei0422
ping
/ping
master

搜索帮助