echo.go 1.1 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 "errors"
  6. // An Echo represenets 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() 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() ([]byte, error) {
  21. b := make([]byte, 4+len(p.Data))
  22. b[0], b[1] = byte(p.ID>>8), byte(p.ID)
  23. b[2], b[3] = byte(p.Seq>>8), byte(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(b []byte) (*Echo, error) {
  29. bodyLen := len(b)
  30. if bodyLen < 4 {
  31. return nil, errors.New("message too short")
  32. }
  33. p := &Echo{ID: int(b[0])<<8 | int(b[1]), Seq: int(b[2])<<8 | int(b[3])}
  34. if bodyLen > 4 {
  35. p.Data = make([]byte, bodyLen-4)
  36. copy(p.Data, b[4:])
  37. }
  38. return p, nil
  39. }