github.com/gopacket/gopacket@v1.1.0/pcap/pcapnggo_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  
     7  package pcap
     8  
     9  import (
    10  	"bytes"
    11  	"io/ioutil"
    12  	"reflect"
    13  	"testing"
    14  	"time"
    15  
    16  	"github.com/gopacket/gopacket"
    17  	"github.com/gopacket/gopacket/layers"
    18  	"github.com/gopacket/gopacket/pcapgo"
    19  )
    20  
    21  func TestPCAPGoNgWrite(t *testing.T) {
    22  	f, err := ioutil.TempFile("", "pcapnggo")
    23  	if err != nil {
    24  		t.Fatal(err)
    25  	}
    26  	data := []byte{0xab, 0xcd, 0xef, 0x01, 0x02, 0x03, 0x04}
    27  	ci := gopacket.CaptureInfo{
    28  		Timestamp:     time.Unix(12345667, 1234567123),
    29  		Length:        700,
    30  		CaptureLength: len(data),
    31  	}
    32  	func() {
    33  		defer f.Close()
    34  		w, err := pcapgo.NewNgWriter(f, layers.LinkTypeEthernet)
    35  		if err != nil {
    36  			t.Fatal(err)
    37  		}
    38  		if err := w.WritePacket(ci, data); err != nil {
    39  			t.Fatal(err)
    40  		}
    41  		if err := w.Flush(); err != nil {
    42  			t.Fatal(err)
    43  		}
    44  	}()
    45  	h, err := OpenOffline(f.Name())
    46  	if err != nil {
    47  		t.Fatal(err)
    48  	}
    49  	defer h.Close()
    50  	gotData, gotCI, err := h.ReadPacketData()
    51  	if err != nil {
    52  		t.Fatal("could not read first packet:", err)
    53  	}
    54  	if !bytes.Equal(gotData, data) {
    55  		t.Errorf("byte mismatch:\nwant: %v\n got: %v", data, gotData)
    56  	}
    57  	if !reflect.DeepEqual(ci, gotCI) {
    58  		t.Errorf("CI mismatch:\nwant: %v\n got: %v", ci, gotCI)
    59  	}
    60  }