golang实现ping命令
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// taken from http://golang.org/src/pkg/net/ipraw_test.go
package ping
import (
"bytes"
"errors"
"net"
"os"
"time"
)
const (
icmpv4EchoRequest = 8
icmpv4EchoReply = 0
icmpv6EchoRequest = 128
icmpv6EchoReply = 129
)
type icmpMessage struct {
Type int // type
Code int // code
Checksum int // checksum
Body icmpMessageBody // body
}
type icmpMessageBody interface {
Len() int
Marshal() ([]byte, error)
}
// Marshal returns the binary enconding of the ICMP echo request or
// reply message m.
func (m *icmpMessage) Marshal() ([]byte, error) {
b := []byte{byte(m.Type), byte(m.Code), 0, 0}
if m.Body != nil && m.Body.Len() != 0 {
mb, err := m.Body.Marshal()
if err != nil {
return nil, err
}
b = append(b, mb...)
}
switch m.Type {
case icmpv6EchoRequest, icmpv6EchoReply:
return b, nil
}
csumcv := len(b) - 1 // checksum coverage
s := uint32(0)
for i := 0; i < csumcv; i += 2 {
s += uint32(b[i+1])<<8 | uint32(b[i])
}
if csumcv&1 == 0 {
s += uint32(b[csumcv])
}
s = s>>16 + s&0xffff
s = s + s>>16
// Place checksum back in header; using ^= avoids the
// assumption the checksum bytes are zero.
b[2] ^= byte(^s & 0xff)
b[3] ^= byte(^s >> 8)
return b, nil
}
// parseICMPMessage parses b as an ICMP message.
func parseICMPMessage(b []byte) (*icmpMessage, error) {
msglen := len(b)
if msglen < 4 {
return nil, errors.New("message too short")
}
m := &icmpMessage{Type: int(b[0]), Code: int(b[1]), Checksum: int(b[2])<<8 | int(b[3])}
if msglen > 4 {
var err error
switch m.Type {
case icmpv4EchoRequest, icmpv4EchoReply, icmpv6EchoRequest, icmpv6EchoReply:
m.Body, err = parseICMPEcho(b[4:])
if err != nil {
return nil, err
}
}
}
return m, nil
}
// imcpEcho represenets an ICMP echo request or reply message body.
type icmpEcho struct {
ID int // identifier
Seq int // sequence number
Data []byte // data
}
func (p *icmpEcho) Len() int {
if p == nil {
return 0
}
return 4 + len(p.Data)
}
// Marshal returns the binary enconding of the ICMP echo request or
// reply message body p.
func (p *icmpEcho) Marshal() ([]byte, error) {
b := make([]byte, 4+len(p.Data))
b[0], b[1] = byte(p.ID>>8), byte(p.ID&0xff)
b[2], b[3] = byte(p.Seq>>8), byte(p.Seq&0xff)
copy(b[4:], p.Data)
return b, nil
}
// parseICMPEcho parses b as an ICMP echo request or reply message body.
func parseICMPEcho(b []byte) (*icmpEcho, error) {
bodylen := len(b)
p := &icmpEcho{ID: int(b[0])<<8 | int(b[1]), Seq: int(b[2])<<8 | int(b[3])}
if bodylen > 4 {
p.Data = make([]byte, bodylen-4)
copy(p.Data, b[4:])
}
return p, nil
}
func Ping(address string, timeout int) (alive bool) {
err := Pinger(address, timeout)
alive = err == nil
return
}
func Pinger(address string, timeout int) (err error) {
c, err := net.Dial("ip4:icmp", address)
if err != nil {
return
}
c.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
defer c.Close()
typ := icmpv4EchoRequest
xid, xseq := os.Getpid()&0xffff, 1
wb, err := (&icmpMessage{
Type: typ, Code: 0,
Body: &icmpEcho{
ID: xid, Seq: xseq,
Data: bytes.Repeat([]byte("Go Go Gadget Ping!!!"), 3),
},
}).Marshal()
if err != nil {
return
}
if _, err = c.Write(wb); err != nil {
return
}
var m *icmpMessage
rb := make([]byte, 20+len(wb))
for {
if _, err = c.Read(rb); err != nil {
return
}
rb = ipv4Payload(rb)
if m, err = parseICMPMessage(rb); err != nil {
return
}
switch m.Type {
case icmpv4EchoRequest, icmpv6EchoRequest:
continue
}
break
}
return
}
func ipv4Payload(b []byte) []byte {
if len(b) < 20 {
return b
}
hdrlen := int(b[0]&0x0f) << 2
return b[hdrlen:]
}
golang实现ping命令的更多相关文章
- Docker的ubuntu镜像安装的容器无ifconfig和ping命令的解决
Docker的Ubuntu镜像安装的容器无ifconfig命令和ping命令 解决: apt-get update apt install net-tools # ifconfig apt ...
- windows 环境和linux环境下 ping命令的区别:
Ping 是Windows自带的一个DOS命令.利用它可以检查网络是否能够连通,用好它可以很好地帮助我们分析判定网络故障.该命令可以加许多参数使用,键入Ping按回车即可看到详细说明.Ping 命令可 ...
- ping命令执行过程详解
[TOC] ping命令执行过程详解 机器A ping 机器B 同一网段 ping通知系统建立一个固定格式的ICMP请求数据包 ICMP协议打包这个数据包和机器B的IP地址转交给IP协议层(一组后台运 ...
- ping命令脚本实现显示网络状态、学生姓名、学号
#!/bin/bash a=. ####定义一个固定变量 h=(wanghao xieyunshen 刘桃) ####定义数组 ..} ####for循环,后面的in是条件即从多少循环到多少 do # ...
- [小菜随笔]python tkinter实现简单的ping命令
本文主要是介绍python图形界面上的按键与实际功能的对接,其实编程掌握了基础之后的学习应该都是靠自己去挖掘其他的 在网上发现多半教程都是2的,故本文使用的是python3.5,其实也没什么区别,就有 ...
- cmd中用PING命令时,出现'Ping' 不是内部或外部命令 解决方案
在cmd中用PING命令时,出现'Ping' 不是内部或外部命令,也不是可运行的程序或批处理文件.先了解一下内容:1.可执行文件.命令文件和批处理文件以.exe或者.com或者.bat为扩展名的文件分 ...
- ping命令
ping命令能够用于判断一个主机是否可达或者是否存活.它的工作原理就像潜水艇的探测原理一样.该命令通过向目标计算机发送一个数据包,请求目标计算机回送该数据包以表明自己还存活着.同时该命令还能够知道数据 ...
- 每天一个linux命令(54):ping命令
Linux系统的ping命令是常用的网络命令,它通常用来测试与目标主机的连通性,我们经常会说“ping一下某机器,看是不是开着”.不能打开网页时会说“你先ping网关地址192.168.1.1试试”. ...
- PING命令入门详解
转自:http://www.linkwan.com/gb/tech/htm/928.htm 1.Ping的基础知识 ping命令相信大家已经再熟悉不过了,但是能把ping的功能发挥到最大的人却并不是很 ...
随机推荐
- No.002 Add Two Numbers
Add Two Numbers Total Accepted: 160702 Total Submissions: 664770 Difficulty: Medium You are given tw ...
- h5 吸顶效果 顶部悬浮
window.onscroll = function(){ var scrollTop = document.documentElement.scrollTop || document.body.sc ...
- FreeBSD下查看各软件版本命令
查看FreeBSD版本: uname -a root# uname -a FreeBSD power 8.1-RELEASE FreeBSD 8.1-RELEASE #0: Mon Jul 19 02 ...
- APUE第五章:标准IO库
5.2流和file对象 #include <wchar.h> int fwide(FILE *fp, int mode); Returns: positive if stream is w ...
- curl返回常见错误码
转自:http://blog.csdn.net/cwj649956781/article/details/8086337 CURLE_OK() 所有罚款.继续像往常一样. CURLE_UNSUPPOR ...
- about control %CPU
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #define timesize 200000 ...
- Android IOS WebRTC 音视频开发总结(五二)-- 亲,咱一起采访webrtc大会的各路专家
本文最早发自我的微信公众号,咱一起采访webrtc大会的各路专家,文章来自博客园RTC.Blacker,支持原创,转载必须说明出处. 亲,作为webrtc大会的推动者之一,大会期间不管是公共场合还是私 ...
- .NET如何从配置文件中获取连接字符串
一.设置配置文件 <configuration> <!--在configuration下创建一个connectionStrings--> <connectionStrin ...
- 开始记录blog
将自己的总结.新的记录下来,形成习惯,为以后的温故知新
- oracle 数组类型
create or replace function my_test(p_str varchar2) return number as --普通变量 v_var ); --固定长度数组 type v_ ...