1、Go语言网络编程:ICMP示例代码 icmptest.go
1 package main 2 3 import ( 4 "fmt" 5 "net" 6 "os" 7 "io" 8 "bytes" 9 ) 10 11 func main() { 12 if len(os.Args) != 2 { 13 fmt.Println("Usage : ", os.Args[0], "host") 14 os.Exit(0) 15 } 16 service := os.Args[1] 17 18 conn, err := net.Dial("ip4:icmp", service) 19 checkError(err) 20 21 var msg [512]byte 22 msg[0] = 8 23 msg[1] = 0 24 msg[2] = 0 25 msg[3] = 0 26 msg[4] = 0 27 msg[5] = 13 28 msg[6] = 0 29 msg[7] = 37 30 len := 8 31 check := checkSum(msg[0:len]) 32 msg[2] = byte(check >> 8) 33 msg[3] = byte(check & 255) 34 35 _, err = conn.Write(msg[0:len]) 36 checkError(err) 37 38 fmt.Println("Got response") 39 if msg[5] == 13 { 40 fmt.Println("Identifier matches") 41 } 42 if msg[7] == 37 { 43 fmt.Println("Sequence matches") 44 } 45 46 os.Exit(0) 47 } 48 49 func checkSum(msg []byte) uint16 { 50 sum := 0 51 52 for n := 1; n < len(msg) - 1; n += 2 { 53 sum += int(msg[n]) * 256 + int(msg[n+1]) 54 } 55 sum = (sum >> 16 ) + (sum & 0xffff) 56 sum += (sum >> 16) 57 var answer uint16 = uint16(^sum) 58 return answer 59 } 60 61 func checkError(err error) { 62 if err != nil { 63 fmt.Fprintf(os.Stderr, "Fatal error : %s\n", err.Error()) 64 os.Exit(1) 65 } 66 } 67 68 func readFully(conn net.Conn) ([]byte, error) { 69 defer conn.Close() 70 71 result := bytes.NewBuffer(nil) 72 var buf [512]byte 73 for { 74 n, err := conn.Read(buf[0:]) 75 result.Write(buf[0:n]) 76 if err != nil { 77 if err == io.EOF { 78 break 79 } 80 return nil, err 81 } 82 } 83 84 return result.Bytes(), nil 85 }
2、编译及运行
$ go build icmptest.go $ ls icmptest icmptest.go $ ./icmptest www.baidu.com Got response Identifier matches Sequence matches
本文转自郝峰波博客园博客,原文链接:http://www.cnblogs.com/fengbohello/p/4663059.html,如需转载请自行联系原作者