github.com/gopacket/gopacket@v1.1.0/pcap/pcapgo_test.go (about) 1 // Copyright 2012 Google, Inc. 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 TestPCAPGoWrite(t *testing.T) { 22 f, err := ioutil.TempFile("", "pcapgo") 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, 1234567000), 29 Length: 700, 30 CaptureLength: len(data), 31 } 32 func() { 33 defer f.Close() 34 w := pcapgo.NewWriter(f) 35 if err := w.WriteFileHeader(65536, layers.LinkTypeEthernet); err != nil { 36 t.Fatal(err) 37 } 38 if err := w.WritePacket(ci, data); err != nil { 39 t.Fatal(err) 40 } 41 }() 42 h, err := OpenOffline(f.Name()) 43 if err != nil { 44 t.Fatal(err) 45 } 46 defer h.Close() 47 gotData, gotCI, err := h.ReadPacketData() 48 if err != nil { 49 t.Fatal("could not read first packet:", err) 50 } 51 if !bytes.Equal(gotData, data) { 52 t.Errorf("byte mismatch:\nwant: %v\n got: %v", data, gotData) 53 } 54 if !reflect.DeepEqual(ci, gotCI) { 55 t.Errorf("CI mismatch:\nwant: %v\n got: %v", ci, gotCI) 56 } 57 }