github.com/gopacket/gopacket@v1.1.0/pcap/bpf_test.go (about)

     1  // Copyright 2018 The GoPacket Authors. All rights reserved.
     2  //
     3  // Use of this source code is governed by a BSD-style license
     4  // that can be found in the LICENSE file in the root of the source
     5  // tree.
     6  package pcap
     7  
     8  import (
     9  	"testing"
    10  	"time"
    11  
    12  	"github.com/gopacket/gopacket"
    13  	"github.com/gopacket/gopacket/layers"
    14  )
    15  
    16  var (
    17  	snaplen = 65535
    18  	packet  = [...]byte{
    19  		0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // dst mac
    20  		0x0, 0x11, 0x22, 0x33, 0x44, 0x55, // src mac
    21  		0x08, 0x0, // ether type
    22  		0x45, 0x0, 0x0, 0x3c, 0xa6, 0xc3, 0x40, 0x0, 0x40, 0x06, 0x3d, 0xd8, // ip header
    23  		0xc0, 0xa8, 0x50, 0x2f, // src ip
    24  		0xc0, 0xa8, 0x50, 0x2c, // dst ip
    25  		0xaf, 0x14, // src port
    26  		0x0, 0x50, // dst port
    27  	}
    28  	matchingBPFFilter    = "ip and tcp and port 80"
    29  	nonmatchingBPFFilter = "udp and port 80"
    30  )
    31  
    32  func BenchmarkPcapNonmatchingBPFFilter(b *testing.B) {
    33  	bpf, err := NewBPF(layers.LinkTypeEthernet, snaplen, nonmatchingBPFFilter)
    34  	if err != nil {
    35  		b.Fatal("incorrect filter")
    36  	}
    37  
    38  	ci := gopacket.CaptureInfo{
    39  		InterfaceIndex: 0,
    40  		CaptureLength:  len(packet),
    41  		Length:         len(packet),
    42  		Timestamp:      time.Now(),
    43  	}
    44  
    45  	for i := 0; i < b.N; i++ {
    46  		if bpf.Matches(ci, packet[:]) {
    47  			b.Fatal("filter must not match the packet")
    48  		}
    49  	}
    50  }
    51  
    52  func BenchmarkPcapMatchingBPFFilter(b *testing.B) {
    53  	bpf, err := NewBPF(layers.LinkTypeEthernet, snaplen, matchingBPFFilter)
    54  	if err != nil {
    55  		b.Fatal("incorrect filter")
    56  	}
    57  
    58  	ci := gopacket.CaptureInfo{
    59  		InterfaceIndex: 0,
    60  		CaptureLength:  len(packet),
    61  		Length:         len(packet),
    62  		Timestamp:      time.Now(),
    63  	}
    64  
    65  	for i := 0; i < b.N; i++ {
    66  		if !bpf.Matches(ci, packet[:]) {
    67  			b.Fatal("filter must match the packet")
    68  		}
    69  	}
    70  }