package mainimport ( "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)}总结
以上是内存溢出为你收集整理的golang实现icmp中的ping功能全部内容,希望文章能够帮你解决golang实现icmp中的ping功能所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)