This is a creation in Article, where the information may have evolved or changed.
ICMP is a protocol used to respond to network conditions, which can be used to detect network status or detect Web errors.
Limited to the current Golang in the network programming code is scarce, the data is very small, so share a golang to construct the ICMP packet and send the PING program echo message instance.
RFC792 defines the ECHO packet structure:
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Code | Checksum | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Identifier | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data ... +-+-+-+-+-
Code:
Package Mainimport ("bytes" "Encoding/binary" "FMT" "net") type ICMP struct {type Uint8code uint8checksum UIn T16identifier uint16sequencenum uint16}func CheckSum (data []byte) uint16 {var (sum uint32length int = len (data) index int) for length > 1 {sum + = UInt32 (Data[index]) <<8 + uint32 (data[index+1]) index + 2length-= 2}if length > 0 { Sum + = UInt32 (Data[index])}sum + = (sum >>) return uint16 (^sum)}func main () {var (ICMP icmpladdr net. IPADDR = net. Ipaddr{ip:net. Parseip ("192.168.137.111")}//***IP address is changed to your own segment ***raddr net. IPADDR = net. Ipaddr{ip:net. Parseip ("192.168.137.1")})//If you want to use the network layer of other protocols can also be set to IP:OSPF, Ip:arp and other conn, err: = Net. Dialip ("ip4:icmp", &laddr, &RADDR) if err! = Nil {fmt. Println (Err. Error ()) Return}defer Conn. Close ()//starts populating the packet with ICMP. Type = 8//8->echo message 0->reply messageicmp. Code = 0icmp. Checksum = 0icmp. Identifier = 0icmp. Sequencenum = 0var (buffer bytes. Buffer)//write the ICMP datagram in buffer to seek checksum binary. Write (&buffer, Binary. BigendIan, ICMP) ICMP. Checksum = Checksum (buffer. Bytes ())//Then empty buffer and write the ICMP datagram of the checksum to prepare to send buffer. Reset () binary. Write (&buffer, Binary. Bigendian, ICMP) If _, err: = conn. Write (buffer. Bytes ()); Err! = Nil {fmt. Println (Err. Error ()) return}fmt. Printf ("Send ICMP packet success!")}
After execution can use Wireshark grasp the package to see, you can see the remote gateway came to the reply response:
See if the ICMP we constructed is correct:
If reproduced please specify the source: http://blog.csdn.net/gophers/article/details/21481447