golang实现icmp中的ping功能

前端之家收集整理的这篇文章主要介绍了golang实现icmp中的ping功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main

import (
	"fmt"
	"net"
	"os"
)

func checkSum(msg []byte) uint16 {
	sum := 0

	len := len(msg)
	for i := 0; i < len-1; i += 2 {
		sum += int(msg[i])*256 + int(msg[i+1])
	}
	if len%2 == 1 {
		sum += int(msg[len-1]) * 256 // notice here,why *256?
	}

	sum = (sum >> 16) + (sum & 0xffff)
	sum += (sum >> 16)
	var answer uint16 = uint16(^sum)
	return answer
}

func checkError(err error) {
	if err != nil {
		fmt.Fprint(os.Stderr,"Fatal error:",err.Error())
		os.Exit(1)
	}
}

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: ",os.Args[0],"host")
		os.Exit(1)
	}

	service := os.Args[1]

	conn,err := net.Dial("ip4:icmp",service)
	checkError(err)

	var msg [512]byte
	msg[0] = 8
	msg[1] = 0
	msg[2] = 0
	msg[3] = 0
	msg[4] = 0
	msg[5] = 13
	msg[6] = 0
	msg[7] = 37
	msg[8] = 99
	len := 9
	check := checkSum(msg[0:len])
	msg[2] = byte(check >> 8)
	msg[3] = byte(check & 0xff)
	fmt.Println(msg[0:len])

	_,err = conn.Write(msg[0:len])
	checkError(err)

	_,err = conn.Read(msg[0:])
	checkError(err)
	fmt.Println(msg[0 : 20+len])

	fmt.Println("Got response")
	if msg[20+5] == 13 {
		fmt.Println("Identifier matches")
	}
	if msg[20+7] == 37 {
		fmt.Println("Sequence matches")
	}
	if msg[20+8] == 99 {
		fmt.Println("Custom data matches")
	}

	os.Exit(0)
}
原文链接:https://www.f2er.com/go/190738.html

猜你在找的Go相关文章