1 Star 0 Fork 0

cgutech-golang/core

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ping.go 2.17 KB
一键复制 编辑 原始数据 按行查看 历史
// Copyright 2019 Yang ZhongXi
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package core
import (
"net"
"time"
)
const echoRequestHeadLen = 8
// Ping PING指令,PING通了立即返回, host:IP地址, times: PING次数
func Ping(host string, times int) bool {
conn, err := net.DialTimeout("ip4:icmp", host, time.Duration(time.Second))
if err != nil {
return false
}
defer conn.Close()
id0, id1 := host[0], host[1]
seq := 1
for times > 0 {
times--
msg := []byte{
0x08, // 报文类型, 8-回显消息
0x00, // 请求和应答,都为0
0x00, 0x00, // 校验码
id0, id1, // ID标识符
byte((seq >> 8) & 0xFF), byte(seq & 0xFF), // 序列号
}
msg = append(msg, make([]byte, 32)...) // 数据内容
msg = append(msg, checkSum(msg)...)
conn.SetDeadline(time.Now().Add(time.Duration(time.Second)))
_, err = conn.Write(msg)
if err != nil {
return false
}
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
continue
}
if n > 32 {
return true
}
}
return false
}
func checkSum(data []byte) []byte {
var (
sum uint32
length int = len(data)
index int
)
//以每16位为单位进行求和,直到所有的字节全部求完或者只剩下一个8位字节(如果剩余一个8位字节说明字节数为奇数个)
for length > 1 {
sum += uint32(data[index])<<8 + uint32(data[index+1])
index += 2
length -= 2
}
//如果字节数为奇数个,要加上最后剩下的那个8位字节
if length > 0 {
sum += uint32(data[index])
}
//加上高16位进位的部分
sum += (sum >> 16)
//别忘了返回的时候先求反
sum = ^sum
return []byte{byte((sum >> 8) & 0xFF), byte(sum & 0xFF)}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/cgutech-golang/core.git
git@gitee.com:cgutech-golang/core.git
cgutech-golang
core
core
v1.0.5

搜索帮助