David K. Bainbridge | 215e024 | 2017-09-05 23:18:24 -0700 | [diff] [blame] | 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 | |
| 5 | package icmp |
| 6 | |
| 7 | import "encoding/binary" |
| 8 | |
| 9 | // An Echo represents an ICMP echo request or reply message body. |
| 10 | type Echo struct { |
| 11 | ID int // identifier |
| 12 | Seq int // sequence number |
| 13 | Data []byte // data |
| 14 | } |
| 15 | |
| 16 | // Len implements the Len method of MessageBody interface. |
| 17 | func (p *Echo) Len(proto int) int { |
| 18 | if p == nil { |
| 19 | return 0 |
| 20 | } |
| 21 | return 4 + len(p.Data) |
| 22 | } |
| 23 | |
| 24 | // Marshal implements the Marshal method of MessageBody interface. |
| 25 | func (p *Echo) Marshal(proto int) ([]byte, error) { |
| 26 | b := make([]byte, 4+len(p.Data)) |
| 27 | binary.BigEndian.PutUint16(b[:2], uint16(p.ID)) |
| 28 | binary.BigEndian.PutUint16(b[2:4], uint16(p.Seq)) |
| 29 | copy(b[4:], p.Data) |
| 30 | return b, nil |
| 31 | } |
| 32 | |
| 33 | // parseEcho parses b as an ICMP echo request or reply message body. |
| 34 | func parseEcho(proto int, b []byte) (MessageBody, error) { |
| 35 | bodyLen := len(b) |
| 36 | if bodyLen < 4 { |
| 37 | return nil, errMessageTooShort |
| 38 | } |
| 39 | p := &Echo{ID: int(binary.BigEndian.Uint16(b[:2])), Seq: int(binary.BigEndian.Uint16(b[2:4]))} |
| 40 | if bodyLen > 4 { |
| 41 | p.Data = make([]byte, bodyLen-4) |
| 42 | copy(p.Data, b[4:]) |
| 43 | } |
| 44 | return p, nil |
| 45 | } |