1. Code
2. Compiling and Running
1. Go Language network programming: ICMP sample code ICMPTEST.GO
1 Package Main2 3 Import (4 "FMT"5 "Net"6 "OS"7 "io"8 "bytes"9 )Ten One Func Main () { A ifLen (OS. Args)! =2 { -Fmt. Println ("Usage:", OS. args[0],"Host") -Os. Exit (0) the } -Service: = OS. args[1] - -Conn, Err: = Net. Dial ("ip4:icmp", service) + checkerror (Err) - + varmsg [ +]byte Amsg[0] =8 atmsg[1] =0 -msg[2] =0 -msg[3] =0 -msg[4] =0 -msg[5] = - -msg[6] =0 inmsg[7] =Panax Notoginseng -Len: =8 toCheck: = CheckSum (msg[0: Len]) +msg[2] =byte(Check >>8) -msg[3] =byte(Check &255) the *_, Err = conn. Write (msg[0: Len]) $ checkerror (Err)Panax Notoginseng -Fmt. Println ("Got Response") the ifmsg[5] == - { +Fmt. Println ("Identifier matches") A } the ifmsg[7] ==Panax Notoginseng { +Fmt. Println ("Sequence matches") - } $ $Os. Exit (0) - } - theFunc checkSum (msg []byte) UInt16 { -Sum: =0Wuyi the forN: =1; n < len (msg)-1; n + =2 { -Sum + =int(Msg[n]) * the+int(msg[n+1]) Wu } -sum = (Sum >> -) + (Sum &0xFFFF) Aboutsum + = (sum >> -) $ varAnswer UInt16 = uint16 (^sum) - returnAnswer - } - A func checkerror (err error) { + ifErr! =Nil { theFmt. fprintf (OS. Stderr,"Fatal Error:%s\n", Err. Error ()) -Os. Exit (1) $ } the } the theFunc readfully (Conn net. Conn) ([]byte, error) { the defer Conn. Close () - inResult: =bytes. Newbuffer (nil) the varBUF [ +]byte the for { AboutN, err: = conn. Read (buf[0:]) theResult. Write (buf[0: n]) the ifErr! =Nil { the ifErr = =io. EOF { + Break - } the returnNil, errBayi } the } the - returnresult. Bytes (), nil -}
2. Compiling and Running
$ go Build icmptest.go $ lsicmptest icmptest.go$. /icmptest www.baidu.comGot responseidentifier matchessequence matches
Go language exercise: Network Programming ICMP Example