echo.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package icmp
  5. import "encoding/binary"
  6. // An Echo represents an ICMP echo request or reply message body.
  7. type Echo struct {
  8. ID int // identifier
  9. Seq int // sequence number
  10. Data []byte // data
  11. }
  12. // Len implements the Len method of MessageBody interface.
  13. func (p *Echo) Len(proto int) int {
  14. if p == nil {
  15. return 0
  16. }
  17. return 4 + len(p.Data)
  18. }
  19. // Marshal implements the Marshal method of MessageBody interface.
  20. func (p *Echo) Marshal(proto int) ([]byte, error) {
  21. b := make([]byte, 4+len(p.Data))
  22. binary.BigEndian.PutUint16(b[:2], uint16(p.ID))
  23. binary.BigEndian.PutUint16(b[2:4], uint16(p.Seq))
  24. copy(b[4:], p.Data)
  25. return b, nil
  26. }
  27. // parseEcho parses b as an ICMP echo request or reply message body.
  28. func parseEcho(proto int, b []byte) (MessageBody, error) {
  29. bodyLen := len(b)
  30. if bodyLen < 4 {
  31. return nil, errMessageTooShort
  32. }
  33. p := &Echo{ID: int(binary.BigEndian.Uint16(b[:2])), Seq: int(binary.BigEndian.Uint16(b[2:4]))}
  34. if bodyLen > 4 {
  35. p.Data = make([]byte, bodyLen-4)
  36. copy(p.Data, b[4:])
  37. }
  38. return p, nil
  39. }