golang.org/x/net@v0.25.1-0.20240516223405-c87a5b62e243/icmp/packettoobig.go (about)

     1  // Copyright 2014 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  // A PacketTooBig represents an ICMP packet too big message body.
    10  type PacketTooBig struct {
    11  	MTU  int    // maximum transmission unit of the nexthop link
    12  	Data []byte // data, known as original datagram field
    13  }
    14  
    15  // Len implements the Len method of MessageBody interface.
    16  func (p *PacketTooBig) Len(proto int) int {
    17  	if p == nil {
    18  		return 0
    19  	}
    20  	return 4 + len(p.Data)
    21  }
    22  
    23  // Marshal implements the Marshal method of MessageBody interface.
    24  func (p *PacketTooBig) Marshal(proto int) ([]byte, error) {
    25  	b := make([]byte, 4+len(p.Data))
    26  	binary.BigEndian.PutUint32(b[:4], uint32(p.MTU))
    27  	copy(b[4:], p.Data)
    28  	return b, nil
    29  }
    30  
    31  // parsePacketTooBig parses b as an ICMP packet too big message body.
    32  func parsePacketTooBig(proto int, _ Type, b []byte) (MessageBody, error) {
    33  	bodyLen := len(b)
    34  	if bodyLen < 4 {
    35  		return nil, errMessageTooShort
    36  	}
    37  	p := &PacketTooBig{MTU: int(binary.BigEndian.Uint32(b[:4]))}
    38  	if bodyLen > 4 {
    39  		p.Data = make([]byte, bodyLen-4)
    40  		copy(p.Data, b[4:])
    41  	}
    42  	return p, nil
    43  }