github.com/gopacket/gopacket@v1.1.0/examples/pcapdump/main.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 // The pcapdump binary implements a tcpdump-like command line tool with gopacket 8 // using pcap as a backend data collection mechanism. 9 package main 10 11 import ( 12 "flag" 13 "fmt" 14 "log" 15 "os" 16 "strings" 17 "time" 18 19 "github.com/gopacket/gopacket/dumpcommand" 20 "github.com/gopacket/gopacket/examples/util" 21 "github.com/gopacket/gopacket/pcap" 22 ) 23 24 var iface = flag.String("i", "eth0", "Interface to read packets from") 25 var fname = flag.String("r", "", "Filename to read from, overrides -i") 26 var snaplen = flag.Int("s", 65536, "Snap length (number of bytes max to read per packet") 27 var tstype = flag.String("timestamp_type", "", "Type of timestamps to use") 28 var promisc = flag.Bool("promisc", true, "Set promiscuous mode") 29 30 func main() { 31 defer util.Run()() 32 var handle *pcap.Handle 33 var err error 34 if *fname != "" { 35 if handle, err = pcap.OpenOffline(*fname); err != nil { 36 log.Fatal("PCAP OpenOffline error:", err) 37 } 38 } else { 39 // This is a little complicated because we want to allow all possible options 40 // for creating the packet capture handle... instead of all this you can 41 // just call pcap.OpenLive if you want a simple handle. 42 inactive, err := pcap.NewInactiveHandle(*iface) 43 if err != nil { 44 log.Fatalf("could not create: %v", err) 45 } 46 defer inactive.CleanUp() 47 if err = inactive.SetSnapLen(*snaplen); err != nil { 48 log.Fatalf("could not set snap length: %v", err) 49 } else if err = inactive.SetPromisc(*promisc); err != nil { 50 log.Fatalf("could not set promisc mode: %v", err) 51 } else if err = inactive.SetTimeout(time.Second); err != nil { 52 log.Fatalf("could not set timeout: %v", err) 53 } 54 if *tstype != "" { 55 if t, err := pcap.TimestampSourceFromString(*tstype); err != nil { 56 log.Fatalf("Supported timestamp types: %v", inactive.SupportedTimestamps()) 57 } else if err := inactive.SetTimestampSource(t); err != nil { 58 log.Fatalf("Supported timestamp types: %v", inactive.SupportedTimestamps()) 59 } 60 } 61 if handle, err = inactive.Activate(); err != nil { 62 log.Fatal("PCAP Activate error:", err) 63 } 64 defer handle.Close() 65 } 66 if len(flag.Args()) > 0 { 67 bpffilter := strings.Join(flag.Args(), " ") 68 fmt.Fprintf(os.Stderr, "Using BPF filter %q\n", bpffilter) 69 if err = handle.SetBPFFilter(bpffilter); err != nil { 70 log.Fatal("BPF filter error:", err) 71 } 72 } 73 dumpcommand.Run(handle) 74 }