Package afpacket provides Go bindings for MMap'd AF_PACKET socket reading.



    View Source
    const (
    	// TPacketVersionHighestAvailable tells NewHandle to use the highest available version of tpacket the kernel has available.
    	// This is the default, should a version number not be given in NewHandle's options.
    	TPacketVersionHighestAvailable = OptTPacketVersion(-1)
    	TPacketVersion1                = OptTPacketVersion(unix.TPACKET_V1)
    	TPacketVersion2                = OptTPacketVersion(unix.TPACKET_V2)
    	TPacketVersion3                = OptTPacketVersion(unix.TPACKET_V3)
    	// SocketRaw is the default socket type.  It returns packet data
    	// including the link layer (ethernet headers, etc).
    	SocketRaw = OptSocketType(unix.SOCK_RAW)
    	// SocketDgram strips off the link layer when reading packets, and adds
    	// the link layer back automatically on packet writes (coming soon...)
    	SocketDgram = OptSocketType(unix.SOCK_DGRAM)

      TPacket version numbers for use with NewHandle.

      View Source
      const (
      	DefaultFrameSize    = 4096                   // Default value for OptFrameSize.
      	DefaultBlockSize    = DefaultFrameSize * 128 // Default value for OptBlockSize.
      	DefaultNumBlocks    = 128                    // Default value for OptNumBlocks.
      	DefaultBlockTimeout = 64 * time.Millisecond  // Default value for OptBlockTimeout.
      	DefaultPollTimeout  = -1 * time.Millisecond  // Default value for OptPollTimeout. This blocks forever.

        Default constants used by options.


        View Source
        var ErrPoll = errors.New("packet poll failed")

          ErrPoll returned by poll

          View Source
          var ErrTimeout = errors.New("packet poll timeout expired")

            ErrTimeout returned on poll timeout


            This section is empty.


            type AncillaryVLAN

            type AncillaryVLAN struct {
            	// The VLAN VID provided by the kernel.
            	VLAN int

              AncillaryVLAN structures are used to pass the captured VLAN as ancillary data via CaptureInfo.

              type FanoutType

              type FanoutType int

                FanoutType determines the type of fanout to use with a TPacket SetFanout call.

                const (
                	FanoutHash FanoutType = unix.PACKET_FANOUT_HASH
                	// It appears that defrag only works with FanoutHash, see:
                	FanoutHashWithDefrag FanoutType = unix.PACKET_FANOUT_FLAG_DEFRAG
                	FanoutLoadBalance    FanoutType = unix.PACKET_FANOUT_LB
                	FanoutCPU            FanoutType = unix.PACKET_FANOUT_CPU
                	FanoutRollover       FanoutType = unix.PACKET_FANOUT_ROLLOVER
                	FanoutRandom         FanoutType = unix.PACKET_FANOUT_RND
                	FanoutQueueMapping   FanoutType = unix.PACKET_FANOUT_QM
                	FanoutCBPF           FanoutType = unix.PACKET_FANOUT_CBPF
                	FanoutEBPF           FanoutType = unix.PACKET_FANOUT_EBPF

                  FanoutType values.

                  type OptAddVLANHeader

                  type OptAddVLANHeader bool

                    OptAddVLANHeader modifies the packet data that comes back from the kernel by adding in the VLAN header that the NIC stripped. AF_PACKET by default uses VLAN offloading, in which the NIC strips the VLAN header off of the packet before handing it to the kernel. This means that, even if a packet has an 802.1q header on the wire, it'll show up without one by the time it goes through AF_PACKET. If this option is true, the VLAN header is added back in before the packet is returned. Note that this potentially has a large performance hit, especially in otherwise zero-copy operation.

                    Note that if you do not need to have a "real" VLAN layer, it may be preferable to use the VLAN ID provided by the AncillaryVLAN struct in CaptureInfo.AncillaryData, which is populated out-of-band and has negligible performance impact. Such ancillary data will automatically be provided if available.

                    type OptBlockSize

                    type OptBlockSize int

                      OptBlockSize is TPacket's tp_block_size It can be passed into NewTPacket.

                      type OptBlockTimeout

                      type OptBlockTimeout time.Duration

                        OptBlockTimeout is TPacket v3's tp_retire_blk_tov. Note that it has only millisecond granularity, so must be >= 1 ms. It can be passed into NewTPacket.

                        type OptFrameSize

                        type OptFrameSize int

                          OptFrameSize is TPacket's tp_frame_size It can be passed into NewTPacket.

                          type OptInterface

                          type OptInterface string

                            OptInterface is the specific interface to bind to. It can be passed into NewTPacket.

                            type OptNumBlocks

                            type OptNumBlocks int

                              OptNumBlocks is TPacket's tp_block_nr It can be passed into NewTPacket.

                              type OptPollTimeout

                              type OptPollTimeout time.Duration

                                OptPollTimeout is the number of milliseconds that poll() should block waiting for a file descriptor to become ready. Specifying a negative value in time‐out means an infinite timeout.

                                type OptSocketType

                                type OptSocketType int

                                  OptSocketType is the socket type used to open the TPacket socket.

                                  func (OptSocketType) String

                                  func (t OptSocketType) String() string

                                  type OptTPacketVersion

                                  type OptTPacketVersion int

                                    OptTPacketVersion is the version of TPacket to use. It can be passed into NewTPacket.

                                    func (OptTPacketVersion) String

                                    func (t OptTPacketVersion) String() string

                                      String returns a string representation of the version, generally of the form V#.

                                      type SocketStats

                                      type SocketStats C.struct_tpacket_stats

                                        SocketStats is a struct where socket stats are stored

                                        func (*SocketStats) Drops

                                        func (s *SocketStats) Drops() uint

                                          Drops returns the number of packets dropped on this socket.

                                          func (*SocketStats) Packets

                                          func (s *SocketStats) Packets() uint

                                            Packets returns the number of packets seen by this socket.

                                            type SocketStatsV3

                                            type SocketStatsV3 C.struct_tpacket_stats_v3

                                              SocketStatsV3 is a struct where socket stats for TPacketV3 are stored

                                              func (*SocketStatsV3) Drops

                                              func (s *SocketStatsV3) Drops() uint

                                                Drops returns the number of packets dropped on this socket.

                                                func (*SocketStatsV3) Packets

                                                func (s *SocketStatsV3) Packets() uint

                                                  Packets returns the number of packets seen by this socket.

                                                  func (*SocketStatsV3) QueueFreezes

                                                  func (s *SocketStatsV3) QueueFreezes() uint

                                                    QueueFreezes returns the number of queue freezes on this socket.

                                                    type Stats

                                                    type Stats struct {
                                                    	// Packets is the total number of packets returned to the caller.
                                                    	Packets int64
                                                    	// Polls is the number of blocking syscalls made waiting for packets.
                                                    	// This should always be <= Packets, since with TPacket one syscall
                                                    	// can (and often does) return many results.
                                                    	Polls int64

                                                      Stats is a set of counters detailing the work TPacket has done so far.

                                                      type TPacket

                                                      type TPacket struct {
                                                      	// contains filtered or unexported fields

                                                        TPacket implements packet receiving for Linux AF_PACKET versions 1, 2, and 3.

                                                        func NewTPacket

                                                        func NewTPacket(opts ...interface{}) (h *TPacket, err error)

                                                          NewTPacket returns a new TPacket object for reading packets off the wire. Its behavior may be modified by passing in any/all of afpacket.Opt* to this function. If this function succeeds, the user should be sure to Close the returned TPacket when finished with it.

                                                          func (*TPacket) Close

                                                          func (h *TPacket) Close()

                                                            Close cleans up the TPacket. It should not be used after the Close call.

                                                            func (*TPacket) InitSocketStats

                                                            func (h *TPacket) InitSocketStats() error

                                                              InitSocketStats clears socket counters and return empty stats.

                                                              func (*TPacket) ReadPacketData

                                                              func (h *TPacket) ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error)

                                                                ReadPacketData reads the next packet, copies it into a new buffer, and returns that buffer. Since the buffer is allocated by ReadPacketData, it is safe for long-term use. This implements gopacket.PacketDataSource.

                                                                func (*TPacket) ReadPacketDataTo

                                                                func (h *TPacket) ReadPacketDataTo(data []byte) (ci gopacket.CaptureInfo, err error)

                                                                  ReadPacketDataTo reads packet data into a user-supplied buffer. This function reads up to the length of the passed-in slice. The number of bytes read into data will be returned in ci.CaptureLength, which is the minimum of the size of the passed-in buffer and the size of the captured packet.

                                                                  func (*TPacket) SetBPF

                                                                  func (h *TPacket) SetBPF(filter []bpf.RawInstruction) error

                                                                    SetBPF attaches a BPF filter to the underlying socket

                                                                    func (*TPacket) SetFanout

                                                                    func (h *TPacket) SetFanout(t FanoutType, id uint16) error

                                                                      SetFanout activates TPacket's fanout ability. Use of Fanout requires creating multiple TPacket objects and the same id/type to a SetFanout call on each. Note that this can be done cross-process, so if two different processes both call SetFanout with the same type/id, they'll share packets between them. The same should work for multiple TPacket objects within the same process.

                                                                      func (*TPacket) SocketStats

                                                                      func (h *TPacket) SocketStats() (SocketStats, SocketStatsV3, error)

                                                                        SocketStats saves stats from the socket to the TPacket instance.

                                                                        func (*TPacket) Stats

                                                                        func (h *TPacket) Stats() (Stats, error)

                                                                          Stats returns statistics on the packets the TPacket has seen so far.

                                                                          func (*TPacket) WritePacketData

                                                                          func (h *TPacket) WritePacketData(pkt []byte) error

                                                                            WritePacketData transmits a raw packet.

                                                                            func (*TPacket) ZeroCopyReadPacketData

                                                                            func (h *TPacket) ZeroCopyReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error)

                                                                              ZeroCopyReadPacketData reads the next packet off the wire, and returns its data. The slice returned by ZeroCopyReadPacketData points to bytes owned by the TPacket. Each call to ZeroCopyReadPacketData invalidates any data previously returned by ZeroCopyReadPacketData. Care must be taken not to keep pointers to old bytes when using ZeroCopyReadPacketData... if you need to keep data past the next time you call ZeroCopyReadPacketData, use ReadPacketData, which copies the bytes into a new buffer for you.

                                                                              tp, _ := NewTPacket(...)
                                                                              data1, _, _ := tp.ZeroCopyReadPacketData()
                                                                              // do everything you want with data1 here, copying bytes out of it if you'd like to keep them around.
                                                                              data2, _, _ := tp.ZeroCopyReadPacketData()  // invalidates bytes in data1