gopacket

package module
v1.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 15, 2014 License: BSD-3-Clause Imports: 10 Imported by: 0

README

# GoPacket

This library provides packet decoding capabilities for Go.
See doc.go for more details.

Originally forked from the gopcap project written by Andreas
Krennmair <ak@synflood.at> (http://github.com/akrennmair/gopcap).

Documentation

Overview

Package gopacket provides packet decoding for the Go language.

gopacket contains many sub-packages with additional functionality you may find useful, including:

  • layers: You'll probably use this every time. This contains of the logic built into gopacket for decoding packet protocols. Note that all example code below assumes that you have imported both gopacket and gopacket/layers.
  • pcap: C bindings to use libpcap to read packets off the wire.
  • pfring: C bindings to use PF_RING to read packets off the wire.
  • afpacket: C bindings for Linux's AF_PACKET to read packets off the wire.
  • tcpassembly: TCP stream reassembly

Also, if you're looking to dive right into code, see the examples subdirectory for numerous simple binaries built using gopacket libraries.

Basic Usage

gopacket takes in packet data as a []byte and decodes it into a packet with a non-zero number of "layers". Each layer corresponds to a protocol within the bytes. Once a packet has been decoded, the layers of the packet can be requested from the packet.

// Decode a packet
packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Default)
// Get the TCP layer from this packet
if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
  fmt.Println("This is a TCP packet!")
  // Get actual TCP data from this layer
  tcp, _ := tcpLayer.(*layers.TCP)
  fmt.Printf("From src port %d to dst port %d\n", tcp.SrcPort, tcp.DstPort)
}
// Iterate over all layers, printing out each layer type
for layer := range packet.Layers() {
  fmt.Println("PACKET LAYER:", layer.LayerType())
}

Packets can be decoded from a number of starting points. Many of our base types implement Decoder, which allow us to decode packets for which we don't have full data.

// Decode an ethernet packet
ethP := gopacket.NewPacket(p1, layers.LayerTypeEthernet, gopacket.Default)
// Decode an IPv6 header and everything it contains
ipP := gopacket.NewPacket(p2, layers.LayerTypeIPv6, gopacket.Default)
// Decode a TCP header and its payload
tcpP := gopacket.NewPacket(p3, layers.LayerTypeTCP, gopacket.Default)

Reading Packets From A Source

Most of the time, you won't just have a []byte of packet data lying around. Instead, you'll want to read packets in from somewhere (file, interface, etc) and process them. To do that, you'll want to build a PacketSource.

First, you'll need to construct an object that implements the PacketDataSource interface. There are implementations of this interface bundled with gopacket in the gopacket/pcap and gopacket/pfring subpackages... see their documentation for more information on their usage. Once you have a PacketDataSource, you can pass it into NewPacketSource, along with a Decoder of your choice, to create a PacketSource.

Once you have a PacketSource, you can read packets from it in multiple ways. See the docs for PacketSource for more details. The easiest method is the Packets function, which returns a channel, then asynchronously writes new packets into that channel, closing the channel if the packetSource hits an end-of-file.

packetSource := ...  // construct using pcap or pfring
for packet := range packetSource.Packets() {
  handlePacket(packet)  // do something with each packet
}

You can change the decoding options of the packetSource by setting fields in packetSource.DecodeOptions... see the following sections for more details.

Lazy Decoding

gopacket optionally decodes packet data lazily, meaning it only decodes a packet layer when it needs to handle a function call.

// Create a packet, but don't actually decode anything yet
packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy)
// Now, decode the packet up to the first IPv4 layer found but no further.
// If no IPv4 layer was found, the whole packet will be decoded looking for
// it.
ip4 := packet.Layer(layers.LayerTypeIPv4)
// Decode all layers and return them.  The layers up to the first IPv4 layer
// are already decoded, and will not require decoding a second time.
layers := packet.Layers()

Lazily-decoded packets are not concurrency-safe. Since layers have not all been decoded, each call to Layer() or Layers() has the potential to mutate the packet in order to decode the next layer. If a packet is used in multiple goroutines concurrently, don't use gopacket.Lazy. Then gopacket will decode the packet fully, and all future function calls won't mutate the object.

NoCopy Decoding

By default, gopacket will copy the slice passed to NewPacket and store the copy within the packet, so future mutations to the bytes underlying the slice don't affect the packet and its layers. If you can guarantee that the underlying slice bytes won't be changed, you can use NoCopy to tell gopacket.NewPacket, and it'll use the passed-in slice itself.

// This channel returns new byte slices, each of which points to a new
// memory location that's guaranteed immutable for the duration of the
// packet.
for data := range myByteSliceChannel {
  p := gopacket.NewPacket(data, layers.LayerTypeEthernet, gopacket.NoCopy)
  doSomethingWithPacket(p)
}

The fastest method of decoding is to use both Lazy and NoCopy, but note from the many caveats above that for some implementations either or both may be dangerous.

Pointers To Known Layers

During decoding, certain layers are stored in the packet as well-known layer types. For example, IPv4 and IPv6 are both considered NetworkLayer layers, while TCP and UDP are both TransportLayer layers. We support 4 layers, corresponding to the 4 layers of the TCP/IP layering scheme (roughly anagalous to layers 2, 3, 4, and 7 of the OSI model). To access these, you can use the packet.LinkLayer, packet.NetworkLayer, packet.TransportLayer, and packet.ApplicationLayer functions. Each of these functions returns a corresponding interface (gopacket.{Link,Network,Transport,Application}Layer). The first three provide methods for getting src/dst addresses for that particular layer, while the final layer provides a Payload function to get payload data. This is helpful, for example, to get payloads for all packets regardless of their underlying data type:

// Get packets from some source
for packet := range someSource {
  if app := packet.ApplicationLayer(); app != nil {
    if strings.Contains(string(app.Payload()), "magic string") {
      fmt.Println("Found magic string in a packet!")
    }
  }
}

A particularly useful layer is ErrorLayer, which is set whenever there's an error parsing part of the packet.

packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Default)
if err := packet.ErrorLayer(); err != nil {
  fmt.Println("Error decoding some part of the packet:", err)
}

Note that we don't return an error from NewPacket because we may have decoded a number of layers successfully before running into our erroneous layer. You may still be able to get your Ethernet and IPv4 layers correctly, even if your TCP layer is malformed.

Flow And Endpoint

gopacket has two useful objects, Flow and Endpoint, for communicating in a protocol independent manner the fact that a packet is coming from A and going to B. The general layer types LinkLayer, NetworkLayer, and TransportLayer all provide methods for extracting their flow information, without worrying about the type of the underlying Layer.

A Flow is a simple object made up of a set of two Endpoints, one source and one destination. It details the sender and receiver of the Layer of the Packet.

An Endpoint is a hashable representation of a source or destination. For example, for LayerTypeIPv4, an Endpoint contains the IP address bytes for a v4 IP packet. A Flow can be broken into Endpoints, and Endpoints can be combined into Flows:

packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy)
netFlow := packet.NetworkLayer().NetworkFlow()
src, dst := netFlow.Endpoints()
reverseFlow := gopacket.NewFlow(dst, src)

Both Endpoint and Flow objects can be used as map keys, and the equality operator can compare them, so you can easily group together all packets based on endpoint criteria:

flows := map[gopacket.Endpoint]chan gopacket.Packet
packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy)
// Send all TCP packets to channels based on their destination port.
if tcp := packet.Layer(layers.LayerTypeTCP); tcp != nil {
  flows[tcp.TransportFlow().Dst()] <- packet
}
// Look for all packets with the same source and destination network address
if net := packet.NetworkLayer(); net != nil {
  src, dst := net.NetworkFlow().Endpoints()
  if src == dst {
    fmt.Println("Fishy packet has same network source and dst: %s", src)
  }
}
// Find all packets coming from UDP port 1000 to UDP port 500
interestingFlow := gopacket.NewFlow(layers.NewUDPPortEndpoint(1000), layers.NewUDPPortEndpoint(500))
if t := packet.NetworkLayer(); t != nil && t.TransportFlow() == interestingFlow {
  fmt.Println("Found that UDP flow I was looking for!")
}

For load-balancing purposes, both Flow and Endpoint have FastHash() functions, which provide quick, non-cryptographic hashes of their contents. Of particular importance is the fact that Flow FastHash() is symetric: A->B will have the same hash as B->A. An example usage could be:

channels := [8]chan gopacket.Packet
for i := 0; i < 8; i++ {
  channels[i] = make(chan gopacket.Packet)
  go packetHandler(channels[i])
}
for packet := range getPackets() {
  if net := packet.NetworkLayer(); net != nil {
    channels[int(net.NetworkFlow().FastHash()) & 0x7] <- packet
  }
}

This allows us to split up a packet stream while still making sure that each stream sees all packets for a flow (and its bidirectional opposite).

Implementing Your Own Decoder

If your network has some strange encapsulation, you can implement your own decoder. In this example, we handle Ethernet packets which are encapsulated in a 4-byte header.

// Create a layer type, should be unique and high, so it doesn't conflict,
// giving it a name and a decoder to use.
var MyLayerType = gopacket.RegisterLayerType(12345, "MyLayerType", gopacket.DecodeFunc(decodeMyLayer))

// Implement my layer
type MyLayer struct {
  StrangeHeader []byte
  payload []byte
}
func (m MyLayer) LayerType() LayerType { return MyLayerType }
func (m MyLayer) LayerContents() []byte { return m.StrangeHeader }
func (m MyLayer) LayerPayload() []byte { return m.payload }

// Now implement a decoder... this one strips off the first 4 bytes of the
// packet.
func decodeMyLayer(data []byte, p gopacket.PacketBuilder) error {
  // Create my layer
  p.AddLayer(&MyLayer{data[:4], data[4:]})
  // Determine how to handle the rest of the packet
  return p.NextDecoder(layers.LayerTypeEthernet)
}

// Finally, decode your packets:
p := gopacket.NewPacket(data, MyLayerType, gopacket.Lazy)

See the docs for Decoder and PacketBuilder for more details on how coding decoders works, or look at RegisterLayerType and RegisterEndpointType to see how to add layer/endpoint types to gopacket.

Fast Decoding With DecodingLayerParser

TLDR: DecodingLayerParser takes about 10% of the time as NewPacket to decode packet data, but only for known packet stacks.

Basic decoding using gopacket.NewPacket or PacketSource.Packets is somewhat slow due to its need to allocate a new packet and every respective layer. It's very versatile and can handle all known layer types, but sometimes you really only care about a specific set of layers regardless, so that versatility is wasted.

DecodingLayerParser avoids memory allocation altogether by decoding packet layers directly into preallocated objects, which you can then reference to get the packet's information. A quick example:

func main() {
  var eth layers.Ethernet
  var ip4 layers.IPv4
  var ip6 layers.IPv6
  var tcp layers.TCP
  parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, &eth, &ip4, &ip6, &tcp)
  decoded := []gopacket.LayerType{}
  for packetData := range somehowGetPacketData() {
    err := parser.DecodeLayers(packetDat, &decoded)
    for _, layerType := range decoded {
      switch layerType {
        case layers.LayerTypeIPv6:
          fmt.Println("    IP4 ", ip4.SrcIP, ip4.DstIP)
        case layers.LayerTypeIPv4:
          fmt.Println("    IP6 ", ip6.SrcIP, ip6.DstIP)
      }
    }
  }
}

The important thing to note here is that the parser is modifying the passed in layers (eth, ip4, ip6, tcp) instead of allocating new ones, thus greatly speeding up the decoding process. It's even branching based on layer type... it'll handle an (eth, ip4, tcp) or (eth, ip6, tcp) stack. However, it won't handle any other type... since no other decoders were passed in, an (eth, ip4, udp) stack will stop decoding after ip4, and only pass back [LayerTypeEthernet, LayerTypeIPv4] through the 'decoded' slice (along with an error saying it can't decode a UDP packet).

Unfortunately, not all layers can be used by DecodingLayerParser... only those implementing the DecodingLayer interface are usable. Also, it's possible to create DecodingLayers that are not themselves Layers... see layers.IPv6ExtensionSkipper for an example of this.

Creating Packet Data

As well as offering the ability to decode packet data, gopacket will allow you to create packets from scratch, as well. A number of gopacket layers implement the SerializableLayer interface; these layers can be serialized to a []byte in the following manner:

ip := &layers.IPv4{
  SrcIP: net.IP{1, 2, 3, 4},
  DstIP: net.IP{5, 6, 7, 8},
  // etc...
}
buf := gopacket.NewSerializeBuffer()
opts := gopacket.SerializeOptions{}  // See SerializeOptions for more details.
err := ip.SerializeTo(&buf, opts)
if err != nil { panic(err) }
fmt.Println(buf.Bytes())  // prints out a byte slice containing the serialized IPv4 layer.

SerializeTo PREPENDS the given layer onto the SerializeBuffer, and they treat the current buffer's Bytes() slice as the payload of the serializing layer. Therefore, you can serialize an entire packet by serializing a set of layers in reverse order (Payload, then TCP, then IP, then Ethernet, for example). The SerializeBuffer's SerializeLayers function is a helper that does exactly that.

To generate a (empty and useless, because no fields are set) Ethernet(IPv4(TCP(Payload))) packet, for exmaple, you can run:

buf := gopacket.NewSerializeBuffer()
opts := gopacket.SerializeOptions{}
gopacket.SerializeLayers(buf, opts,
  &layers.Ethernet{},
  &layers.IPv4{},
  &layers.TCP{},
  gopacket.Payload([]byte{1, 2, 3, 4}))
packetData := buf.Bytes()

A Final Note

If you use gopacket, you'll almost definitely want to make sure gopacket/layers is imported, since when imported it sets all the LayerType variables and fills in a lot of interesting variables/maps (DecodersByLayerName, etc). Therefore, it's recommended that even if you don't use any layers functions directly, you still import with:

import (
  _ "code.google.com/p/gopacket/layers"
)

Index

Examples

Constants

View Source
const MaxEndpointSize = 16

MaxEndpointSize determines the maximum size in bytes of an endpoint address.

Endpoints/Flows have a problem: They need to be hashable. Therefore, they can't use a byte slice. The two obvious choices are to use a string or a byte array. Strings work great, but string creation requires memory allocation, which can be slow. Arrays work great, but have a fixed size. We originally used the former, now we've switched to the latter. Use of a fixed byte-array doubles the speed of constructing a flow (due to not needing to allocate). This is a huge increase... too much for us to pass up.

The end result of this, though, is that an endpoint/flow can't be created using more than MaxEndpointSize bytes per address.

Variables

View Source
var DecodersByLayerName = map[string]Decoder{}

DecodersByLayerName maps layer names to decoders for those layers. This allows users to specify decoders by name to a program and have that program pick the correct decoder accordingly.

Functions

func LayerDump

func LayerDump(l Layer) string

LayerDump outputs a very verbose string representation of a layer. Its output is a concatenation of LayerString(l) and hex.Dump(l.LayerContents()). It contains newlines and ends with a newline.

func LayerString

func LayerString(l Layer) string

LayerString outputs an individual layer as a string. The layer is output in a single line, with no trailing newline. This function is specifically designed to do the right thing for most layers... it follows the following rules:

  • If the Layer has a String function, just output that.
  • Otherwise, output all exported fields in the layer, recursing into exported slices and structs.

NOTE: This is NOT THE SAME AS fmt's "%#v". %#v will output both exported and unexported fields... many times packet layers contain unexported stuff that would just mess up the output of the layer, see for example the Payload layer and it's internal 'data' field, which contains a large byte array that would really mess up formatting.

func SerializeLayers

func SerializeLayers(w SerializeBuffer, opts SerializeOptions, layers ...SerializableLayer) error

SerializeLayers clears the given write buffer, then writes all layers into it so they correctly wrap each other. Note that by clearing the buffer, it invalidates all slices previously returned by w.Bytes()

Example:

buf := gopacket.NewSerializeBuffer()
opts := gopacket.SerializeOptions{}
gopacket.SerializeLayers(buf, opts, a, b, c)
firstPayload := buf.Bytes()  // contains byte representation of a(b(c))
gopacket.SerializeLayers(buf, opts, d, e, f)
secondPayload := buf.Bytes()  // contains byte representation of d(e(f)). firstPayload is now invalidated, since the SerializeLayers call Clears buf.

Types

type ApplicationLayer

type ApplicationLayer interface {
	Layer
	Payload() []byte
}

ApplicationLayer is the packet layer corresponding to the TCP/IP layer 4 (OSI layer 7), also known as the packet payload.

type CaptureInfo

type CaptureInfo struct {
	// Timestamp is the time the packet was captured, if that is known.
	Timestamp time.Time
	// CaptureLength is the total number of bytes read off of the wire.
	CaptureLength int
	// Length is the size of the original packet.  Should always be >=
	// CaptureLength.
	Length int
}

CaptureInfo provides standardized information about a packet captured off the wire or read from a file.

type DecodeFailure

type DecodeFailure struct {
	// contains filtered or unexported fields
}

DecodeFailure is a packet layer created if decoding of the packet data failed for some reason. It implements ErrorLayer. LayerContents will be the entire set of bytes that failed to parse, and Error will return the reason parsing failed.

func (*DecodeFailure) Dump

func (d *DecodeFailure) Dump() (s string)

func (*DecodeFailure) Error

func (d *DecodeFailure) Error() error

Error returns the error encountered during decoding.

func (*DecodeFailure) LayerContents

func (d *DecodeFailure) LayerContents() []byte

func (*DecodeFailure) LayerPayload

func (d *DecodeFailure) LayerPayload() []byte

func (*DecodeFailure) LayerType

func (d *DecodeFailure) LayerType() LayerType

LayerType returns LayerTypeDecodeFailure

func (*DecodeFailure) String

func (d *DecodeFailure) String() string

type DecodeFeedback

type DecodeFeedback interface {
	// SetTruncated should be called if during decoding you notice that a packet
	// is shorter than internal layer variables (HeaderLength, or the like) say it
	// should be.  It sets packet.Metadata().Truncated.
	SetTruncated()
}

DecodeFeedback is used by DecodingLayer layers to provide decoding metadata.

var NilDecodeFeedback DecodeFeedback = nilDecodeFeedback{}

NilDecodeFeedback implements DecodeFeedback by doing nothing.

type DecodeFunc

type DecodeFunc func([]byte, PacketBuilder) error

DecodeFunc wraps a function to make it a Decoder.

func (DecodeFunc) Decode

func (d DecodeFunc) Decode(data []byte, p PacketBuilder) error

type DecodeOptions

type DecodeOptions struct {
	// Lazy decoding decodes the minimum number of layers needed to return data
	// for a packet at each function call.  Be careful using this with concurrent
	// packet processors, as each call to packet.* could mutate the packet, and
	// two concurrent function calls could interact poorly.
	Lazy bool
	// NoCopy decoding doesn't copy its input buffer into storage that's owned by
	// the packet.  If you can guarantee that the bytes underlying the slice
	// passed into NewPacket aren't going to be modified, this can be faster.  If
	// there's any chance that those bytes WILL be changed, this will invalidate
	// your packets.
	NoCopy bool
}

DecodeOptions tells gopacket how to decode a packet.

var Default DecodeOptions = DecodeOptions{}

Default decoding provides the safest (but slowest) method for decoding packets. It eagerly processes all layers (so it's concurrency-safe) and it copies its input buffer upon creation of the packet (so the packet remains valid if the underlying slice is modified. Both of these take time, though, so beware. If you can guarantee that the packet will only be used by one goroutine at a time, set Lazy decoding. If you can guarantee that the underlying slice won't change, set NoCopy decoding.

var Lazy DecodeOptions = DecodeOptions{Lazy: true}

Lazy is a DecodeOptions with just Lazy set.

var NoCopy DecodeOptions = DecodeOptions{NoCopy: true}

NoCopy is a DecodeOptions with just NoCopy set.

type Decoder

type Decoder interface {
	// Decode decodes the bytes of a packet, sending decoded values and other
	// information to PacketBuilder, and returning an error if unsuccessful.  See
	// the PacketBuilder documentation for more details.
	Decode([]byte, PacketBuilder) error
}

Decoder is an interface for logic to decode a packet layer. Users may implement a Decoder to handle their own strange packet types, or may use one of the many decoders available in the 'layers' subpackage to decode things for them.

var DecodeFragment Decoder = DecodeFunc(decodeFragment)

DecodeFragment is a Decoder that returns a Fragment layer containing all remaining bytes.

var DecodePayload Decoder = DecodeFunc(decodePayload)

DecodePayload is a Decoder that returns a Payload layer containing all remaining bytes.

var DecodeUnknown Decoder = DecodeFunc(decodeUnknown)

DecodeUnknown is a Decoder that returns an Unknown layer containing all remaining bytes, useful if you run up against a layer that you're unable to decode yet. This layer is considered an ErrorLayer.

type DecodingLayer

type DecodingLayer interface {
	// DecodeFromBytes resets the internal state of this layer to the state
	// defined by the passed-in bytes.  Slices in the DecodingLayer may
	// reference the passed-in data, so care should be taken to copy it
	// first should later modification of data be required before the
	// DecodingLayer is discarded.
	DecodeFromBytes(data []byte, df DecodeFeedback) error
	// CanDecode returns the set of LayerTypes this DecodingLayer can
	// decode.  For Layers that are also DecodingLayers, this will most
	// often be that Layer's LayerType().
	CanDecode() LayerClass
	// NextLayerType returns the LayerType which should be used to decode
	// the LayerPayload.
	NextLayerType() LayerType
	// LayerPayload is the set of bytes remaining to decode after a call to
	// DecodeFromBytes.
	LayerPayload() []byte
}

DecodingLayer is an interface for packet layers that can decode themselves.

The important part of DecodingLayer is that they decode themselves in-place. Calling DecodeFromBytes on a DecodingLayer totally resets the entire layer to the new state defined by the data passed in. A returned error leaves the DecodingLayer in an unknown intermediate state, thus its fields should not be trusted.

Because the DecodingLayer is resetting its own fields, a call to DecodeFromBytes should normally not require any memory allocation.

type DecodingLayerParser

type DecodingLayerParser struct {
	// DecodingLayerParserOptions is the set of options available to the
	// user to define the parser's behavior.
	DecodingLayerParserOptions

	// Truncated is set when a decode layer detects that the packet has been
	// truncated.
	Truncated bool
	// contains filtered or unexported fields
}

DecodingLayerParser parses a given set of layer types. See DecodeLayers for more information on how DecodingLayerParser should be used.

func NewDecodingLayerParser

func NewDecodingLayerParser(first LayerType, decoders ...DecodingLayer) *DecodingLayerParser

NewDecodingLayerParser creates a new DecodingLayerParser and adds in all of the given DecodingLayers with AddDecodingLayer.

Each call to DecodeLayers will attempt to decode the given bytes first by treating them as a 'first'-type layer, then by using NextLayerType on subsequently decoded layers to find the next relevant decoder. Should a deoder not be available for the layer type returned by NextLayerType, decoding will stop.

func (*DecodingLayerParser) AddDecodingLayer

func (l *DecodingLayerParser) AddDecodingLayer(d DecodingLayer)

AddDecodingLayer adds a decoding layer to the parser. This adds support for the decoding layer's CanDecode layers to the parser... should they be encountered, they'll be parsed.

func (*DecodingLayerParser) DecodeLayers

func (l *DecodingLayerParser) DecodeLayers(data []byte, decoded *[]LayerType) (err error)

DecodeLayers decodes as many layers as possible from the given data. It initially treats the data as layer type 'typ', then uses NextLayerType on each subsequent decoded layer until it gets to a layer type it doesn't know how to parse.

For each layer successfully decoded, DecodeLayers appends the layer type to the decoded slice. DecodeLayers truncates the 'decoded' slice initially, so there's no need to empty it yourself.

This decoding method is about an order of magnitude faster than packet decoding, because it only decodes known layers that have already been allocated. This means it doesn't need to allocate each layer it returns... instead it overwrites the layers that already exist.

Example usage:

func main() {
  var eth layers.Ethernet
  var ip4 layers.IPv4
  var ip6 layers.IPv6
  var tcp layers.TCP
  var udp layers.UDP
  var payload gopacket.Payload
  parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, &eth, &ip4, &ip6, &tcp, &udp, &payload)
  var source gopacket.PacketDataSource = getMyDataSource()
  decodedLayers := make([]gopacket.LayerType, 0, 10)
  for {
    data, _, err := source.ReadPacketData()
    if err == nil {
      fmt.Println("Error reading packet data: ", err)
      continue
    }
    fmt.Println("Decoding packet")
    err = parser.DecodeLayers(data, &decodedLayers)
    for _, typ := range decodedLayers {
      fmt.Println("  Successfully decoded layer type", typ)
      switch typ {
        case layers.LayerTypeEthernet:
          fmt.Println("    Eth ", eth.SrcMAC, eth.DstMAC)
        case layers.LayerTypeIPv4:
          fmt.Println("    IP4 ", ip4.SrcIP, ip4.DstIP)
        case layers.LayerTypeIPv6:
          fmt.Println("    IP6 ", ip6.SrcIP, ip6.DstIP)
        case layers.LayerTypeTCP:
          fmt.Println("    TCP ", tcp.SrcPort, tcp.DstPort)
        case layers.LayerTypeUDP:
          fmt.Println("    UDP ", udp.SrcPort, udp.DstPort)
      }
    }
    if decodedLayers.Truncated {
      fmt.Println("  Packet has been truncated")
    }
    if err != nil {
      fmt.Println("  Error encountered:", err)
    }
  }
}

If DecodeLayers is unable to decode the next layer type, it will return the error UnsupportedLayerType.

func (*DecodingLayerParser) SetTruncated

func (l *DecodingLayerParser) SetTruncated()

SetTruncated is used by DecodingLayers to set the Truncated boolean in the DecodingLayerParser. Users should simply read Truncated after calling DecodeLayers.

type DecodingLayerParserOptions

type DecodingLayerParserOptions struct {
	// IgnorePanic determines whether a DecodingLayerParser should stop
	// panics on its own (by returning them as an error from DecodeLayers)
	// or should allow them to raise up the stack.  Handling errors does add
	// latency to the process of decoding layers, but is much safer for
	// callers.  IgnorePanic defaults to false, thus if the caller does
	// nothing decode panics will be returned as errors.
	IgnorePanic bool
}

DecodingLayerParserOptions provides options to affect the behavior of a given DecodingLayerParser.

type Dumper

type Dumper interface {
	Dump() string
}

Dumper dumps verbose information on a value. If a layer type implements Dumper, then its LayerDump() string will include the results in its output.

type Endpoint

type Endpoint struct {
	// contains filtered or unexported fields
}

Endpoint is the set of bytes used to address packets at various layers. See LinkLayer, NetworkLayer, and TransportLayer specifications. Endpoints are usable as map keys.

var InvalidEndpoint Endpoint = NewEndpoint(EndpointInvalid, nil)

InvalidEndpoint is a singleton Endpoint of type EndpointInvalid.

func NewEndpoint

func NewEndpoint(typ EndpointType, raw []byte) (e Endpoint)

NewEndpoint creates a new Endpoint object.

The size of raw must be less than MaxEndpointSize, otherwise this function will panic.

func (Endpoint) EndpointType

func (e Endpoint) EndpointType() EndpointType

EndpointType returns the endpoint type associated with this endpoint.

func (Endpoint) FastHash

func (a Endpoint) FastHash() (h uint64)

FastHash provides a quick hashing function for an endpoint, useful if you'd like to split up endpoints by modulos or other load-balancing techniques. It uses a variant of Fowler-Noll-Vo hashing.

The output of FastHash is not guaranteed to remain the same through future code revisions, so should not be used to key values in persistent storage.

func (Endpoint) LessThan

func (a Endpoint) LessThan(b Endpoint) bool

LessThan provides a stable ordering for all endpoints. It sorts first based on the EndpointType of an endpoint, then based on the raw bytes of that endpoint.

For some endpoints, the actual comparison may not make sense, however this ordering does provide useful information for most Endpoint types. Ordering is based first on endpoint type, then on raw endpoint bytes. Endpoint bytes are sorted lexigraphically.

func (Endpoint) Raw

func (e Endpoint) Raw() []byte

Raw returns the raw bytes of this endpoint. These aren't human-readable most of the time, but they are faster than calling String.

func (Endpoint) String

func (e Endpoint) String() string

type EndpointType

type EndpointType int64

EndpointType is the type of a gopacket Endpoint. This type determines how the bytes stored in the endpoint should be interpreted.

var EndpointInvalid EndpointType = RegisterEndpointType(0, EndpointTypeMetadata{"invalid", func(b []byte) string {
	return fmt.Sprintf("%v", b)
}})

EndpointInvalid is an endpoint type used for invalid endpoints, IE endpoints that are specified incorrectly during creation.

func RegisterEndpointType

func RegisterEndpointType(num int, meta EndpointTypeMetadata) EndpointType

RegisterEndpointType creates a new EndpointType and registers it globally. It MUST be passed a unique number, or it will panic. Numbers 0-999 are reserved for gopacket's use.

func (EndpointType) String

func (e EndpointType) String() string

type EndpointTypeMetadata

type EndpointTypeMetadata struct {
	// Name is the string returned by an EndpointType's String function.
	Name string
	// Formatter is called from an Endpoint's String function to format the raw
	// bytes in an Endpoint into a human-readable string.
	Formatter func([]byte) string
}

EndpointTypeMetadata is used to register a new endpoint type.

type ErrorLayer

type ErrorLayer interface {
	Layer
	Error() error
}

ErrorLayer is a packet layer created when decoding of the packet has failed. Its payload is all the bytes that we were unable to decode, and the returned error details why the decoding failed.

type Flow

type Flow struct {
	// contains filtered or unexported fields
}

Flow represents the direction of traffic for a packet layer, as a source and destination Endpoint. Flows are usable as map keys.

var InvalidFlow Flow = NewFlow(EndpointInvalid, nil, nil)

InvalidFlow is a singleton Flow of type EndpointInvalid.

func FlowFromEndpoints

func FlowFromEndpoints(src, dst Endpoint) (_ Flow, err error)

FlowFromEndpoints creates a new flow by pasting together two endpoints. The endpoints must have the same EndpointType, or this function will return an error.

func NewFlow

func NewFlow(t EndpointType, src, dst []byte) (f Flow)

NewFlow creates a new flow.

src and dst must have length <= MaxEndpointSize, otherwise NewFlow will panic.

func (Flow) Dst

func (f Flow) Dst() (dst Endpoint)

Dst returns the destination Endpoint for this flow.

func (Flow) EndpointType

func (f Flow) EndpointType() EndpointType

EndpointType returns the EndpointType for this Flow.

func (Flow) Endpoints

func (f Flow) Endpoints() (src, dst Endpoint)

Endpoints returns the two Endpoints for this flow.

func (Flow) FastHash

func (a Flow) FastHash() (h uint64)

FastHash provides a quick hashing function for a flow, useful if you'd like to split up flows by modulos or other load-balancing techniques. It uses a variant of Fowler-Noll-Vo hashing, and is guaranteed to collide with its reverse flow. IE: the flow A->B will have the same hash as the flow B->A.

The output of FastHash is not guaranteed to remain the same through future code revisions, so should not be used to key values in persistent storage.

func (Flow) Reverse

func (f Flow) Reverse() Flow

Reverse returns a new flow with endpoints reversed.

func (Flow) Src

func (f Flow) Src() (src Endpoint)

Src returns the source Endpoint for this flow.

func (Flow) String

func (f Flow) String() string

String returns a human-readable representation of this flow, in the form "Src->Dst"

type Fragment added in v1.1.6

type Fragment []byte

Fragment is a Layer containing a fragment of a larger frame, used by layers like IPv4 and IPv6 that allow for fragmentation of their payloads.

func (*Fragment) CanDecode added in v1.1.6

func (p *Fragment) CanDecode() LayerClass

func (*Fragment) DecodeFromBytes added in v1.1.6

func (p *Fragment) DecodeFromBytes(data []byte, df DecodeFeedback) error

func (*Fragment) LayerContents added in v1.1.6

func (p *Fragment) LayerContents() []byte

func (*Fragment) LayerPayload added in v1.1.6

func (p *Fragment) LayerPayload() []byte

func (*Fragment) LayerType added in v1.1.6

func (p *Fragment) LayerType() LayerType

LayerType returns LayerTypeFragment

func (*Fragment) NextLayerType added in v1.1.6

func (p *Fragment) NextLayerType() LayerType

func (*Fragment) Payload added in v1.1.6

func (p *Fragment) Payload() []byte

func (*Fragment) SerializeTo added in v1.1.6

func (p *Fragment) SerializeTo(b SerializeBuffer, opts SerializeOptions) error

SerializeTo writes the serialized form of this layer into the SerializationBuffer, implementing gopacket.SerializableLayer. See the docs for gopacket.SerializableLayer for more info.

func (*Fragment) String added in v1.1.6

func (p *Fragment) String() string

type Layer

type Layer interface {
	// LayerType is the gopacket type for this layer.
	LayerType() LayerType
	// LayerContents returns the set of bytes that make up this layer.
	LayerContents() []byte
	// LayerPayload returns the set of bytes contained within this layer, not
	// including the layer itself.
	LayerPayload() []byte
}

Layer represents a single decoded packet layer (using either the OSI or TCP/IP definition of a layer). When decoding, a packet's data is broken up into a number of layers. The caller may call LayerType() to figure out which type of layer they've received from the packet. Optionally, they may then use a type assertion to get the actual layer type for deep inspection of the data.

type LayerClass

type LayerClass interface {
	// Contains returns true if the given layer type should be considered part
	// of this layer class.
	Contains(LayerType) bool
	// LayerTypes returns the set of all layer types in this layer class.
	// Note that this may not be a fast operation on all LayerClass
	// implementations.
	LayerTypes() []LayerType
}

LayerClass is a set of LayerTypes, used for grabbing one of a number of different types from a packet.

func NewLayerClass

func NewLayerClass(types []LayerType) LayerClass

NewLayerClass creates a LayerClass, attempting to be smart about which type it creates based on which types are passed in.

type LayerClassMap

type LayerClassMap map[LayerType]bool

LayerClassMap implements a LayerClass with a map.

func NewLayerClassMap

func NewLayerClassMap(types []LayerType) LayerClassMap

NewLayerClassMap creates a LayerClassMap and sets map[t] to true for each type in types.

func (LayerClassMap) Contains

func (m LayerClassMap) Contains(t LayerType) bool

Contains returns true if the given layer type should be considered part of this layer class.

func (LayerClassMap) LayerTypes

func (m LayerClassMap) LayerTypes() (all []LayerType)

LayerTypes returns all layer types in this LayerClassMap.

type LayerClassSlice

type LayerClassSlice []bool

LayerClassSlice implements a LayerClass with a slice.

func NewLayerClassSlice

func NewLayerClassSlice(types []LayerType) LayerClassSlice

NewLayerClassSlice creates a new LayerClassSlice by creating a slice of size max(types) and setting slice[t] to true for each type t. Note, if you implement your own LayerType and give it a high value, this WILL create a very large slice.

func (LayerClassSlice) Contains

func (s LayerClassSlice) Contains(t LayerType) bool

Contains returns true if the given layer type should be considered part of this layer class.

func (LayerClassSlice) LayerTypes

func (s LayerClassSlice) LayerTypes() (all []LayerType)

LayerTypes returns all layer types in this LayerClassSlice. Because of LayerClassSlice's implementation, this could be quite slow.

type LayerType

type LayerType int64

LayerType is a unique identifier for each type of layer. This enumeration does not match with any externally available numbering scheme... it's solely usable/useful within this library as a means for requesting layer types (see Packet.Layer) and determining which types of layers have been decoded.

New LayerTypes may be created by calling gopacket.RegisterLayerType.

var LayerTypeDecodeFailure LayerType = RegisterLayerType(1, LayerTypeMetadata{"DecodeFailure", DecodeUnknown})

LayerTypeDecodeFailure is the layer type for the default error layer.

var LayerTypeFragment LayerType = RegisterLayerType(3, LayerTypeMetadata{"Fragment", DecodeFragment})

LayerTypeFragment is the layer type for a fragment of a layer transported by an underlying layer that supports fragmentation.

var LayerTypePayload LayerType = RegisterLayerType(2, LayerTypeMetadata{"Payload", DecodePayload})

LayerTypePayload is the layer type for a payload that we don't try to decode but treat as a success, IE: an application-level payload.

var LayerTypeZero LayerType = RegisterLayerType(0, LayerTypeMetadata{"Unknown", DecodeUnknown})

LayerTypeZero is an invalid layer type, but can be used to determine whether layer type has actually been set correctly.

func RegisterLayerType

func RegisterLayerType(num int, meta LayerTypeMetadata) LayerType

RegisterLayerType creates a new layer type and registers it globally. The number passed in must be unique, or a runtime panic will occur. Numbers 0-999 are reserved for the gopacket library. Numbers 1000-1999 should be used for common application-specific types, and are very fast. Any other number (negative or >= 2000) may be used for uncommon application-specific types, and are somewhat slower (they require a map lookup over an array index).

func (LayerType) Contains

func (l LayerType) Contains(a LayerType) bool

Make LayerType itself be a LayerClass.

func (LayerType) Decode

func (t LayerType) Decode(data []byte, c PacketBuilder) error

Decode decodes the given data using the decoder registered with the layer type.

func (LayerType) LayerTypes

func (l LayerType) LayerTypes() []LayerType

func (LayerType) String

func (t LayerType) String() (s string)

String returns the string associated with this layer type.

type LayerTypeMetadata

type LayerTypeMetadata struct {
	// Name is the string returned by each layer type's String method.
	Name string
	// Decoder is the decoder to use when the layer type is passed in as a
	// Decoder.
	Decoder Decoder
}

LayerTypeMetadata contains metadata associated with each LayerType.

type LinkLayer

type LinkLayer interface {
	Layer
	LinkFlow() Flow
}

LinkLayer is the packet layer corresponding to TCP/IP layer 1 (OSI layer 2)

type NetworkLayer

type NetworkLayer interface {
	Layer
	NetworkFlow() Flow
}

NetworkLayer is the packet layer corresponding to TCP/IP layer 2 (OSI layer 3)

type Packet

type Packet interface {
	//// Functions for outputting the packet as a human-readable string:
	//// ------------------------------------------------------------------
	// String returns a human-readable string representation of the packet.
	// It uses LayerString on each layer to output the layer.
	String() string
	// Dump returns a verbose human-readable string representation of the packet,
	// including a hex dump of all layers.  It uses LayerDump on each layer to
	// output the layer.
	Dump() string

	//// Functions for accessing arbitrary packet layers:
	//// ------------------------------------------------------------------
	// Layers returns all layers in this packet, computing them as necessary
	Layers() []Layer
	// Layer returns the first layer in this packet of the given type, or nil
	Layer(LayerType) Layer
	// LayerClass returns the first layer in this packet of the given class,
	// or nil.
	LayerClass(LayerClass) Layer

	//// Functions for accessing specific types of packet layers.  These functions
	//// return the first layer of each type found within the packet.
	//// ------------------------------------------------------------------
	// LinkLayer returns the first link layer in the packet
	LinkLayer() LinkLayer
	// NetworkLayer returns the first network layer in the packet
	NetworkLayer() NetworkLayer
	// TransportLayer returns the first transport layer in the packet
	TransportLayer() TransportLayer
	// ApplicationLayer returns the first application layer in the packet
	ApplicationLayer() ApplicationLayer
	// ErrorLayer is particularly useful, since it returns nil if the packet
	// was fully decoded successfully, and non-nil if an error was encountered
	// in decoding and the packet was only partially decoded.  Thus, its output
	// can be used to determine if the entire packet was able to be decoded.
	ErrorLayer() ErrorLayer

	//// Functions for accessing data specific to the packet:
	//// ------------------------------------------------------------------
	// Data returns the set of bytes that make up this entire packet.
	Data() []byte
	// Metadata returns packet metadata associated with this packet.
	Metadata() *PacketMetadata
}

Packet is the primary object used by gopacket. Packets are created by a Decoder's Decode call. A packet is made up of a set of Data, which is broken into a number of Layers as it is decoded.

func NewPacket

func NewPacket(data []byte, firstLayerDecoder Decoder, options DecodeOptions) Packet

NewPacket creates a new Packet object from a set of bytes. The firstLayerDecoder tells it how to interpret the first layer from the bytes, future layers will be generated from that first layer automatically.

type PacketBuilder

type PacketBuilder interface {
	DecodeFeedback
	// AddLayer should be called by a decoder immediately upon successful
	// decoding of a layer.
	AddLayer(l Layer)
	// The following functions set the various specific layers in the final
	// packet.  Note that if many layers call SetX, the first call is kept and all
	// other calls are ignored.
	SetLinkLayer(LinkLayer)
	SetNetworkLayer(NetworkLayer)
	SetTransportLayer(TransportLayer)
	SetApplicationLayer(ApplicationLayer)
	SetErrorLayer(ErrorLayer)
	// NextDecoder should be called by a decoder when they're done decoding a
	// packet layer but not done with decoding the entire packet.  The next
	// decoder will be called to decode the last AddLayer's LayerPayload.
	// Because of this, NextDecoder must only be called once all other
	// PacketBuilder calls have been made.  Set*Layer and AddLayer calls after
	// NextDecoder calls will behave incorrectly.
	NextDecoder(next Decoder) error
	// DumpPacketData is used solely for decoding.  If you come across an error
	// you need to diagnose while processing a packet, call this and your packet's
	// data will be dumped to stderr so you can create a test.  This should never
	// be called from a production decoder.
	DumpPacketData()
}

PacketBuilder is used by layer decoders to store the layers they've decoded, and to defer future decoding via NextDecoder. Typically, the pattern for use is:

func (m *myDecoder) Decode(data []byte, p PacketBuilder) error {
  if myLayer, err := myDecodingLogic(data); err != nil {
    return err
  } else {
    p.AddLayer(myLayer)
  }
  // maybe do this, if myLayer is a LinkLayer
  p.SetLinkLayer(myLayer)
  return p.NextDecoder(nextDecoder)
}

type PacketDataSource

type PacketDataSource interface {
	// ReadPacketData returns the next packet available from this data source.
	// It returns:
	//  data:  The bytes of an individual packet.
	//  ci:  Metadata about the capture
	//  err:  An error encountered while reading packet data.  If err != nil,
	//    then data/ci will be ignored.
	ReadPacketData() (data []byte, ci CaptureInfo, err error)
}

PacketDataSource is an interface for some source of packet data. Users may create their own implementations, or use the existing implementations in gopacket/pcap (libpcap, allows reading from live interfaces or from pcap files) or gopacket/pfring (PF_RING, allows reading from live interfaces).

type PacketMetadata

type PacketMetadata struct {
	CaptureInfo
	// Truncated is true if packet decoding logic detects that there are fewer
	// bytes in the packet than are detailed in various headers (for example, if
	// the number of bytes in the IPv4 contents/payload is less than IPv4.Length).
	// This is also set automatically for packets captured off the wire if
	// CaptureInfo.CaptureLength < CaptureInfo.Length.
	Truncated bool
}

PacketMetadata contains metadata for a packet.

type PacketSource

type PacketSource struct {

	// DecodeOptions is the set of options to use for decoding each piece
	// of packet data.  This can/should be changed by the user to reflect the
	// way packets should be decoded.
	DecodeOptions
	// contains filtered or unexported fields
}

PacketSource reads in packets from a PacketDataSource, decodes them, and returns them.

There are currently two different methods for reading packets in through a PacketSource:

Reading With Packets Function

This method is the most convenient and easiest to code, but lacks flexibility. Packets returns a 'chan Packet', then asynchronously writes packets into that channel. Packets uses a blocking channel, and closes it if an io.EOF is returned by the underlying PacketDataSource. All other PacketDataSource errors are ignored and discarded.

for packet := range packetSource.Packets() {
  ...
}

Reading With NextPacket Function

This method is the most flexible, and exposes errors that may be encountered by the underlying PacketDataSource. It's also the fastest in a tight loop, since it doesn't have the overhead of a channel read/write. However, it requires the user to handle errors, most importantly the io.EOF error in cases where packets are being read from a file.

for {
  packet, err := packetSource.NextPacket() {
  if err == io.EOF {
    break
  } else if err != nil {
    log.Println("Error:", err)
    continue
  }
  handlePacket(packet)  // Do something with each packet.
}

func NewPacketSource

func NewPacketSource(source PacketDataSource, decoder Decoder) *PacketSource

NewPacketSource creates a packet data source.

func (*PacketSource) NextPacket

func (p *PacketSource) NextPacket() (Packet, error)

NextPacket returns the next decoded packet from the PacketSource. On error, it returns a nil packet and a non-nil error.

func (*PacketSource) Packets

func (p *PacketSource) Packets() chan Packet

Packets returns a channel of packets, allowing easy iterating over packets. Packets will be asynchronously read in from the underlying PacketDataSource and written to the returned channel. If the underlying PacketDataSource returns an io.EOF error, the channel will be closed. If any other error is encountered, it is ignored.

for packet := range packetSource.Packets() {
  handlePacket(packet)  // Do something with each packet.
}

If called more than once, returns the same channel.

type Payload

type Payload []byte

Payload is a Layer containing the payload of a packet. The definition of what constitutes the payload of a packet depends on previous layers; for TCP and UDP, we stop decoding above layer 4 and return the remaining bytes as a Payload. Payload is an ApplicationLayer.

func (Payload) CanDecode

func (p Payload) CanDecode() LayerClass

func (*Payload) DecodeFromBytes

func (p *Payload) DecodeFromBytes(data []byte, df DecodeFeedback) error

func (Payload) LayerContents

func (p Payload) LayerContents() []byte

func (Payload) LayerPayload

func (p Payload) LayerPayload() []byte

func (Payload) LayerType

func (p Payload) LayerType() LayerType

LayerType returns LayerTypePayload

func (Payload) NextLayerType

func (p Payload) NextLayerType() LayerType

func (Payload) Payload

func (p Payload) Payload() []byte

func (Payload) SerializeTo

func (p Payload) SerializeTo(b SerializeBuffer, opts SerializeOptions) error

SerializeTo writes the serialized form of this layer into the SerializationBuffer, implementing gopacket.SerializableLayer. See the docs for gopacket.SerializableLayer for more info.

func (Payload) String

func (p Payload) String() string

type SerializableLayer

type SerializableLayer interface {
	// SerializeTo writes this layer to a slice, growing that slice if necessary
	// to make it fit the layer's data.
	//  Args:
	//   b:  SerializeBuffer to write this layer on to.  When called, b.Bytes()
	//     is the payload this layer should wrap, if any.  Note that this
	//     layer can either prepend itself (common), append itself
	//     (uncommon), or both (sometimes padding or footers are required at
	//     the end of packet data). It's also possible (though probably very
	//     rarely needed) to overwrite any bytes in the current payload.
	//     After this call, b.Bytes() should return the byte encoding of
	//     this layer wrapping the original b.Bytes() payload.
	//   opts:  options to use while writing out data.
	//  Returns:
	//   error if a problem was encountered during encoding.  If an error is
	//   returned, the bytes in data should be considered invalidated, and
	//   not used.
	//
	// SerializeTo calls SHOULD entirely ignore LayerContents and
	// LayerPayload.  It just serializes based on struct fields, neither
	// modifying nor using contents/payload.
	SerializeTo(b SerializeBuffer, opts SerializeOptions) error
}

SerializableLayer allows its implementations to be written out as a set of bytes, so those bytes may be sent on the wire or otherwise used by the caller. SerializableLayer is implemented by certain Layer types, and can be encoded to bytes using the LayerWriter object.

type SerializeBuffer

type SerializeBuffer interface {
	// Bytes returns the contiguous set of bytes collected so far by Prepend/Append
	// calls.  The slice returned by Bytes will be modified by future Clear calls,
	// so if you're planning on clearing this SerializeBuffer, you may want to copy
	// Bytes somewhere safe first.
	Bytes() []byte
	// PrependBytes returns a set of bytes which prepends the current bytes in this
	// buffer.  These bytes start in an indeterminate state, so they should be
	// overwritten by the caller.  The caller must only call PrependBytes if they
	// know they're going to immediately overwrite all bytes returned.
	PrependBytes(num int) ([]byte, error)
	// AppendBytes returns a set of bytes which prepends the current bytes in this
	// buffer.  These bytes start in an indeterminate state, so they should be
	// overwritten by the caller.  The caller must only call AppendBytes if they
	// know they're going to immediately overwrite all bytes returned.
	AppendBytes(num int) ([]byte, error)
	// Clear resets the SerializeBuffer to a new, empty buffer.  After a call to clear,
	// the byte slice returned by any previous call to Bytes() for this buffer
	// should be considered invalidated.
	Clear() error
}

SerializeBuffer is a helper used by gopacket for writing out packet layers. SerializeBuffer starts off as an empty []byte. Subsequent calls to PrependBytes return byte slices before the current Bytes(), AppendBytes returns byte slices after.

Byte slices returned by PrependBytes/AppendBytes are NOT zero'd out, so if you want to make sure they're all zeros, set them as such.

SerializeBuffer is specifically designed to handle packet writing, where unlike with normal writes it's easier to start writing at the inner-most layer and work out, meaning that we often need to prepend bytes. This runs counter to typical writes to byte slices using append(), where we only write at the end of the buffer.

It can be reused via Clear. Note, however, that a Clear call will invalidate the byte slices returned by any previous Bytes() call (the same buffer is reused).

  1. Reusing a write buffer is generally much faster than creating a new one, and with the default implementation it avoids additional memory allocations.
  2. If a byte slice from a previous Bytes() call will continue to be used, it's better to create a new SerializeBuffer.

The Clear method is specifically designed to minimize memory allocations for similar later workloads on the SerializeBuffer. IE: if you make a set of Prepend/Append calls, then clear, then make the same calls with the same sizes, the second round (and all future similar rounds) shouldn't allocate any new memory.

Example
b := NewSerializeBuffer()
fmt.Println("1:", b.Bytes())
bytes, _ := b.PrependBytes(3)
copy(bytes, []byte{1, 2, 3})
fmt.Println("2:", b.Bytes())
bytes, _ = b.AppendBytes(2)
copy(bytes, []byte{4, 5})
fmt.Println("3:", b.Bytes())
bytes, _ = b.PrependBytes(1)
copy(bytes, []byte{0})
fmt.Println("4:", b.Bytes())
bytes, _ = b.AppendBytes(3)
copy(bytes, []byte{6, 7, 8})
fmt.Println("5:", b.Bytes())
b.Clear()
fmt.Println("6:", b.Bytes())
bytes, _ = b.PrependBytes(2)
copy(bytes, []byte{9, 9})
fmt.Println("7:", b.Bytes())
Output:

1: []
2: [1 2 3]
3: [1 2 3 4 5]
4: [0 1 2 3 4 5]
5: [0 1 2 3 4 5 6 7 8]
6: []
7: [9 9]

func NewSerializeBuffer

func NewSerializeBuffer() SerializeBuffer

NewSerializeBuffer creates a new instance of the default implementation of the SerializeBuffer interface.

func NewSerializeBufferExpectedSize

func NewSerializeBufferExpectedSize(expectedPrependLength, expectedAppendLength int) SerializeBuffer

NewSerializeBufferExpectedSize creates a new buffer for serialization, optimized for an expected number of bytes prepended/appended. This tends to decrease the number of memory allocations made by the buffer during writes.

type SerializeOptions

type SerializeOptions struct {
	// FixLengths determines whether, during serialization, layers should fix
	// the values for any length field that depends on the payload.
	FixLengths bool
	// ComputeChecksums determines whether, during serialization, layers
	// should recompute checksums based on their payloads.
	ComputeChecksums bool
}

SerializeOptions provides options for behaviors that SerializableLayers may want to implement.

type TransportLayer

type TransportLayer interface {
	Layer
	TransportFlow() Flow
}

TransportLayer is the packet layer corresponding to the TCP/IP layer 3 (OSI layer 4)

type UnsupportedLayerType

type UnsupportedLayerType LayerType

UnsupportedLayerType is returned by DecodingLayerParser if DecodeLayers encounters a layer type that the DecodingLayerParser has no decoder for.

func (UnsupportedLayerType) Error

func (e UnsupportedLayerType) Error() string

Error implements the error interface, returning a string to say that the given layer type is unsupported.

type ZeroCopyPacketDataSource

type ZeroCopyPacketDataSource interface {
	// ZeroCopyReadPacketData returns the next packet available from this data source.
	// It returns:
	//  data:  The bytes of an individual packet.  Unlike with
	//    PacketDataSource's ReadPacketData, the slice returned here points
	//    to a buffer owned by the data source.  In particular, the bytes in
	//    this buffer may be changed by future calls to
	//    ZeroCopyReadPacketData.  Do not use the returned buffer after
	//    subsequent ZeroCopyReadPacketData calls.
	//  ci:  Metadata about the capture
	//  err:  An error encountered while reading packet data.  If err != nil,
	//    then data/ci will be ignored.
	ZeroCopyReadPacketData() (data []byte, ci CaptureInfo, err error)
}

ZeroCopyPacketDataSource is an interface to pull packet data from sources that allow data to be returned without copying to a user-controlled buffer. It's very similar to PacketDataSource, except that the caller must be more careful in how the returned buffer is handled.

Directories

Path Synopsis
Package afpacket provides Go bindings for MMap'd AF_PACKET socket reading.
Package afpacket provides Go bindings for MMap'd AF_PACKET socket reading.
Package bytediff provides a simple diff utility for looking at differences in byte slices.
Package bytediff provides a simple diff utility for looking at differences in byte slices.
Package dumpcommand implements a run function for pfdump and pcapdump with many similar flags/features to tcpdump.
Package dumpcommand implements a run function for pfdump and pcapdump with many similar flags/features to tcpdump.
examples
arpscan
arpscan implements ARP scanning of all interfaces' local networks using gopacket and its subpackages.
arpscan implements ARP scanning of all interfaces' local networks using gopacket and its subpackages.
bidirectional
This binary provides an example of connecting up bidirectional streams from the unidirectional streams provided by gopacket/tcpassembly.
This binary provides an example of connecting up bidirectional streams from the unidirectional streams provided by gopacket/tcpassembly.
bytediff
This binary shows how to display byte differences to users via the bytediff library.
This binary shows how to display byte differences to users via the bytediff library.
httpassembly
This binary provides sample code for using the gopacket TCP assembler and TCP stream reader.
This binary provides sample code for using the gopacket TCP assembler and TCP stream reader.
pcapdump
The pcapdump binary implements a tcpdump-like command line tool with gopacket using pcap as a backend data collection mechanism.
The pcapdump binary implements a tcpdump-like command line tool with gopacket using pcap as a backend data collection mechanism.
pfdump
The pfdump binary implements a tcpdump-like command line tool with gopacket using pfring as a backend data collection mechanism.
The pfdump binary implements a tcpdump-like command line tool with gopacket using pfring as a backend data collection mechanism.
statsassembly
This binary provides sample code for using the gopacket TCP assembler raw, without the help of the tcpreader library.
This binary provides sample code for using the gopacket TCP assembler raw, without the help of the tcpreader library.
synscan
synscan implements a TCP syn scanner on top of pcap.
synscan implements a TCP syn scanner on top of pcap.
Package layers provides decoding layers for many common protocols.
Package layers provides decoding layers for many common protocols.
Package macs provides an in-memory mapping of all valid Ethernet MAC address prefixes to their associated organization.
Package macs provides an in-memory mapping of all valid Ethernet MAC address prefixes to their associated organization.
Package pcap allows users of gopacket to read packets off the wire or from pcap files.
Package pcap allows users of gopacket to read packets off the wire or from pcap files.
gopacket_benchmark
This benchmark reads in file <tempdir>/gopacket_benchmark.pcap and measures the time it takes to decode all packets from that file.
This benchmark reads in file <tempdir>/gopacket_benchmark.pcap and measures the time it takes to decode all packets from that file.
Package pcapgo provides some native PCAP support, not requiring C libpcap to be installed.
Package pcapgo provides some native PCAP support, not requiring C libpcap to be installed.
Package pfring wraps the PF_RING C library for Go.
Package pfring wraps the PF_RING C library for Go.
Package routing provides a very basic but mostly functional implementation of a routing table for IPv4/IPv6 addresses.
Package routing provides a very basic but mostly functional implementation of a routing table for IPv4/IPv6 addresses.
Package tcpassembly provides TCP stream re-assembly.
Package tcpassembly provides TCP stream re-assembly.
tcpreader
Package tcpreader provides an implementation for tcpassembly.Stream which presents the caller with an io.Reader for easy processing.
Package tcpreader provides an implementation for tcpassembly.Stream which presents the caller with an io.Reader for easy processing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL