echo.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. // An Echo represents an ICMP echo request or reply message body.
  6. type Echo struct {
  7. ID int // identifier
  8. Seq int // sequence number
  9. Data []byte // data
  10. }
  11. // Len implements the Len method of MessageBody interface.
  12. func (p *Echo) Len(proto int) int {
  13. if p == nil {
  14. return 0
  15. }
  16. return 4 + len(p.Data)
  17. }
  18. // Marshal implements the Marshal method of MessageBody interface.
  19. func (p *Echo) Marshal(proto int) ([]byte, error) {
  20. b := make([]byte, 4+len(p.Data))
  21. b[0], b[1] = byte(p.ID>>8), byte(p.ID)
  22. b[2], b[3] = byte(p.Seq>>8), byte(p.Seq)
  23. copy(b[4:], p.Data)
  24. return b, nil
  25. }
  26. // parseEcho parses b as an ICMP echo request or reply message body.
  27. func parseEcho(proto int, b []byte) (MessageBody, error) {
  28. bodyLen := len(b)
  29. if bodyLen < 4 {
  30. return nil, errMessageTooShort
  31. }
  32. p := &Echo{ID: int(b[0])<<8 | int(b[1]), Seq: int(b[2])<<8 | int(b[3])}
  33. if bodyLen > 4 {
  34. p.Data = make([]byte, bodyLen-4)
  35. copy(p.Data, b[4:])
  36. }
  37. return p, nil
  38. }