代码拉取完成,页面将自动刷新
// 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)}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。