示例#1
0
func runTestZone(){
	fmt.Println("We're in test zone")
	if handle, err := pcap.OpenOffline("/home/jnankin/Desktop/test.pcap"); err != nil {
		panic(err)
	} else {
		packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
		for packet := range packetSource.Packets() {
			
			if packet.Layer(layers.LayerTypeTCP) != nil {
				appLayer := packet.ApplicationLayer()
				fmt.Println("APP LAYER: \n" + string(appLayer.Payload()) + "\n\n");
				
				sipMessage := sipparser.ParseMsg(string(appLayer.Payload()))
				fmt.Println("SIP BODY: \n" + sipMessage.Body + "\n\n");
				fmt.Println("Content length: \n" + sipMessage.ContentLength + "\n\n");
				
				/*SIP PDU detection: 1st Line contains SIP/2.0

foreach line, if it's a content length, set it.
    add each line to the current sip message
    if the line is blank:
        if I have a content length:
         add content length more bytes from the message to the current sip message
        
        add the current message to the list of messages found

if there are still messages in the buffer, the packet is fragmented and we need more messages

				*/
			}
		}
	}
}
示例#2
0
func NewPcapFileSniffer(filename string) (*PcapHandle, error) {
	pcapFileHandle, err := pcap.OpenOffline(filename)
	pcapHandle := PcapHandle{
		handle: pcapFileHandle,
	}
	return &pcapHandle, err
}
示例#3
0
文件: benchmark.go 项目: ikravets/ev
func (c *cmdBenchmark) ParsingFinished() (err error) {
	if !c.shouldExecute {
		return
	}
	handle, err := pcap.OpenOffline(c.InputFileName)
	errs.CheckE(err)
	defer handle.Close()

	bo := packet.NewBufferedObtainer(handle)

	var pp packet.Processor
	if c.ProcCopy {
		pp = processor.NewCopyingProcessor()
	} else {
		pp = processor.NewReusingProcessor()
	}
	pp.SetObtainer(bo)

	var totalDuration time.Duration
	for i := 0; i < c.Iter; i++ {
		bo.Reset()
		start := time.Now()
		pp.ProcessAll()
		duration := time.Since(start)
		totalDuration += duration
	}
	timePerPacket := totalDuration / time.Duration(c.Iter*bo.Packets())
	fmt.Printf("total duration: %s, time/pkt: %s\n", totalDuration, timePerPacket)
	return
}
示例#4
0
func TestTCP(t *testing.T) {
	handle, err := pcap.OpenOffline("tcptest.pcap")
	if err != nil {
		panic(err)
	}
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	defer handle.Close()
	tcpPack := make(chan gopacket.Packet, 10)
	nomalPack := make(chan gopacket.Packet, 5)
	for input_pack := range packetSource.Packets() { // send tcp package for channel
		tcpLayer := input_pack.Layer(layers.LayerTypeTCP)
		if tcpLayer != nil {
			tcpPack <- input_pack
			// send packet to tcp ASSEMBLER
		}
	}
	streamFactory := &DNSStreamFactory{normal: nomalPack}
	streamPool := tcpassembly.NewStreamPool(streamFactory)
	assembler := tcpassembly.NewAssembler(streamPool)
	go tcpAssemble(tcpPack, assembler)
	pack := <-nomalPack
	udpLayer := pack.Layer(layers.LayerTypeUDP)
	if udpLayer == nil {
		t.Errorf("can not fine udp Layer in result")
	}
	dns_message := new(dns.Msg)
	err = dns_message.Unpack(udpLayer.LayerPayload())
	if err != nil {
		t.Errorf("can not parse dns message")
	}
	fmt.Printf(dns_message.String())
}
示例#5
0
文件: ng.go 项目: 4lyingli0n/netgraph
func packetSource() *gopacket.PacketSource {
	if *inputPcap != "" {
		handle, err := pcap.OpenOffline(*inputPcap)
		if err != nil {
			log.Fatalln(err)
		}
		fmt.Printf("open pcap file \"%s\"\n", *inputPcap)
		return gopacket.NewPacketSource(handle, handle.LinkType())
	}

	if *device == "" {
		*device = autoSelectDev()
		if *device == "" {
			log.Fatalln("no device to capture")
		}
	}

	handle, err := pcap.OpenLive(*device, 1024*1024, true, pcap.BlockForever)
	if err != nil {
		log.Fatalln(err)
	}
	if *bpf != "" {
		if err = handle.SetBPFFilter(*bpf); err != nil {
			log.Fatalln("Failed to set BPF filter:", err)
		}
	}
	fmt.Printf("open live on device \"%s\", bpf \"%s\", serves on port %d\n", *device, *bpf, *bindingPort)
	return gopacket.NewPacketSource(handle, handle.LinkType())
}
示例#6
0
func main() {
	flag.Parse()

	pcap, err := pcap.OpenOffline(*pcapFile)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error opening pcap file:", err)
		os.Exit(1)
	}
	h := mongocaputils.NewPacketHandler(pcap)
	m := mongocaputils.NewMongoOpStream(*packetBufSize)

	ch := make(chan struct{})
	go func() {
		defer close(ch)
		for op := range m.Ops {
			if _, ok := op.Op.(*mongoproto.OpUnknown); !ok {
				fmt.Printf("%f %v\n", float64(op.Seen.Sub(m.FirstSeen))/10e8, op)
			}
		}
	}()

	if err := h.Handle(m, -1); err != nil {
		fmt.Fprintln(os.Stderr, "mongocapcat: error handling packet stream:", err)
	}
	<-ch
}
示例#7
0
func TestNgnet(t *testing.T) {
	eventChan := make(chan interface{}, 1024)
	f := NewHttpStreamFactory(eventChan)
	pool := tcpassembly.NewStreamPool(f)
	assembler := tcpassembly.NewAssembler(pool)
	packetCount := 0
	fmt.Println("Run")
	if handle, err := pcap.OpenOffline("dump.pcapng"); err != nil {
		panic(err)
	} else {
		packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
		for packet := range packetSource.Packets() {
			net_layer := packet.NetworkLayer()
			trans_layer := packet.TransportLayer()

			if net_layer == nil {
				continue
			}
			if trans_layer == nil {
				continue
			}
			packetCount++
			tcp, _ := trans_layer.(*layers.TCP)
			assembler.AssembleWithTimestamp(net_layer.NetworkFlow(), tcp, packet.Metadata().CaptureInfo.Timestamp)
		}
	}
	assembler.FlushAll()
	f.Wait()
	fmt.Println("packet:", packetCount, "http:", len(eventChan))
}
示例#8
0
func ProcessPackets(pcapFile string,
	mongodHost string,
	mongodPort string) {
	if handle, err := pcap.OpenOffline(pcapFile); err != nil {
		panic(err)
	} else {
		var connectionWaitGroup sync.WaitGroup
		packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
		firstPacket := <-packetSource.Packets()
		packetMinTimestamp = GetPacketTime(firstPacket)
		mapHostConnection = make(map[string]*MongoConnection)
		SendPacket(firstPacket,
			&connectionWaitGroup,
			mongodHost,
			mongodPort)
		for packet := range packetSource.Packets() {
			SendPacket(packet,
				&connectionWaitGroup,
				mongodHost,
				mongodPort)
		}
		for _, mConnection := range mapHostConnection {
			mConnection.EOF()
		}
		connectionWaitGroup.Wait()
	}
}
示例#9
0
文件: snifer.go 项目: influx6/goproj
//init re-initializes a snifer for uses
func (s *Snifer) init() error {
	var handle *pcap.Handle
	var err error

	if s.conf.Offline {
		handle, err = pcap.OpenOffline(s.source)
		checkError(err, fmt.Sprintf("Create offline handle %s", s.source))
	} else {
		handle, err = pcap.OpenLive(s.source, s.conf.MaxPacket, s.conf.Promod, s.conf.Timeout)
		checkError(err, fmt.Sprintf("Create Live handle %s", s.source))

		if err == nil {
			err = handle.SetBPFFilter(s.conf.Filter)
			checkError(err, fmt.Sprintf("Setting BPFFilter %s: %s", s.source, s.conf.Filter))
		}

	}

	if err != nil {
		checkError(err, fmt.Sprintf("Creating Snifer for %s", s.source))
		return err
	}

	s.handle = handle
	log.Printf("Snifer: Handler created and ready!")

	return nil
}
示例#10
0
func pcapInfo(filename string) (start time.Time, end time.Time, packets int, size int) {
	handleRead, err := pcap.OpenOffline(*fname)
	if err != nil {
		log.Fatal("PCAP OpenOffline error (handle to read packet):", err)
	}

	var previousTs time.Time
	var deltaTotal time.Duration

	for {
		data, ci, err := handleRead.ReadPacketData()
		if err != nil && err != io.EOF {
			log.Fatal(err)
		} else if err == io.EOF {
			break
		} else {

			if start.IsZero() {
				start = ci.Timestamp
			}
			end = ci.Timestamp
			packets++
			size += len(data)

			if previousTs.IsZero() {
				previousTs = ci.Timestamp
			} else {
				deltaTotal += ci.Timestamp.Sub(previousTs)
				previousTs = ci.Timestamp
			}
		}
	}
	fmt.Printf("Avg packet rate %d/s\n", packets/int(deltaTotal.Seconds()))
	return start, end, packets, size
}
示例#11
0
文件: main.go 项目: onvoy/udpreplay
func main() {
	flag.Parse()
	var handle *pcap.Handle
	var err error
	if *fname != "" {
		log.Printf("Reading from pcap dump %q", *fname)
		handle, err = pcap.OpenOffline(*fname)
	} else {
		log.Printf("Starting capture on interface %q", *iface)
		handle, err = pcap.OpenLive(*iface, int32(*snaplen), true, pcap.BlockForever)
	}
	if err != nil {
		log.Fatal(err)
	}

	if err := handle.SetBPFFilter(*filter); err != nil {
		log.Fatal(err)
	}

	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		if packet == nil {
			return
		}
		if udpLayer := packet.Layer(layers.LayerTypeUDP); udpLayer != nil {
			udp, _ := udpLayer.(*layers.UDP)
			fwdSIPPacket(udp.BaseLayer.Payload)
		}
	}
}
示例#12
0
文件: main.go 项目: moveman/ts
func main() {
	if len(os.Args) != 2 {
		fmt.Printf("Usage: %s pcap\n", os.Args[0])
		os.Exit(0)
	}

	input, output := os.Args[1], "out.ts"

	handle, err := pcap.OpenOffline(input)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	f, err := os.Create(output)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	source := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range source.Packets() {
		appLayer := packet.ApplicationLayer()
		if appLayer != nil {
			payload := appLayer.Payload()
			if len(payload) == UDPSize {
				f.Write(payload)
			} else if len(payload) == HRTPSize {
				offset := HRTPSize - UDPSize
				f.Write(payload[offset:HRTPSize])
			}
		}
	}
}
示例#13
0
func getOpstream(cfg OpStreamSettings) (*packetHandlerContext, error) {
	if cfg.PacketBufSize < 1 {
		return nil, fmt.Errorf("invalid packet buffer size")
	}

	var pcapHandle *pcap.Handle
	var err error
	if len(cfg.PcapFile) > 0 {
		pcapHandle, err = pcap.OpenOffline(cfg.PcapFile)
		if err != nil {
			return nil, fmt.Errorf("error opening pcap file: %v", err)
		}
	} else if len(cfg.NetworkInterface) > 0 {
		pcapHandle, err = pcap.OpenLive(cfg.NetworkInterface, 32*1024*1024, false, pcap.BlockForever)
		if err != nil {
			return nil, fmt.Errorf("error listening to network interface: %v", err)
		}
	} else {
		return nil, fmt.Errorf("must specify either a pcap file or network interface to record from")
	}

	if len(cfg.Expression) > 0 {
		err = pcapHandle.SetBPFFilter(cfg.Expression)
		if err != nil {
			return nil, fmt.Errorf("error setting packet filter expression: %v", err)
		}
	}

	h := NewPacketHandler(pcapHandle)
	h.Verbose = userInfoLogger.isInVerbosity(DebugLow)

	toolDebugLogger.Logvf(Info, "Created packet buffer size %d", cfg.PacketBufSize)
	m := NewMongoOpStream(cfg.PacketBufSize)
	return &packetHandlerContext{h, m, pcapHandle}, nil
}
示例#14
0
文件: main.go 项目: caoqianli/httpcap
func openFile(pcapFile string) *pcap.Handle {
	handle, err := pcap.OpenOffline(pcapFile)
	if err != nil {
		log.Fatal("Open file", pcapFile, "error:", err)
	}
	return handle
}
示例#15
0
func main() {
	flag.Parse()

	pcap, err := pcap.OpenOffline(*pcapFile)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error opening pcap file:", err)
		os.Exit(1)
	}
	h := mongocaputils.NewPacketHandler(pcap)
	m := mongocaputils.NewMongoOpStream(*packetBufSize)

	ch := make(chan struct{})
	go func() {
		defer close(ch)
		for op := range m.Ops {
			bsonBytes, err := bson.Marshal(op)
			if err != nil {
				fmt.Fprintln(os.Stderr, "error marshaling message:", err)
				os.Exit(1)
			}
			_, err = os.Stdout.Write(bsonBytes)
			if err != nil {
				fmt.Fprintln(os.Stderr, "error writing message:", err)
				os.Exit(1)
			}
		}
	}()

	if err := h.Handle(m, -1); err != nil {
		fmt.Fprintln(os.Stderr, "mongorecord: error handling packet stream:", err)
	}
	<-ch
}
示例#16
0
func main() {
	defer util.Run()()
	var handle *pcap.Handle
	var err error

	// Set up pcap packet capture
	if *fname != "" {
		log.Printf("Reading from pcap dump %q", *fname)
		handle, err = pcap.OpenOffline(*fname)
	} else {
		log.Fatalln("Error: pcap file name is required!")
		// log.Printf("Starting capture on interface %q", *iface)
		// handle, err = pcap.OpenLive(*iface, int32(*snaplen), true, pcap.BlockForever)
	}
	if err != nil {
		log.Fatal(err)
	}

	if err := handle.SetBPFFilter(*filter); err != nil {
		log.Fatal(err)
	}

	// Set up assembly
	streamFactory := &httpStreamFactory{}
	streamPool := tcpassembly.NewStreamPool(streamFactory)
	assembler := tcpassembly.NewAssembler(streamPool)

	log.Println("reading in packets")
	// Read in packets, pass to assembler.
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	packets := packetSource.Packets()
	ticker := time.Tick(time.Minute)
	for {
		select {
		case packet := <-packets:
			// A nil packet indicates the end of a pcap file.
			if packet == nil {
				return
			}
			if *logAllPackets {
				log.Println("\npacket:")
				// log.Println(packet)
			}
			if packet.NetworkLayer() == nil || packet.TransportLayer() == nil || packet.TransportLayer().LayerType() != layers.LayerTypeTCP {
				log.Println("Unusable packet")
				continue
			}
			tcp := packet.TransportLayer().(*layers.TCP)
			log.Printf("\n.......................................................\n")
			log.Printf("packet:\n")
			log.Printf("packet.Metadata().Timestamp=%T=%v=%v:\n%#v\n", packet.Metadata().Timestamp, packet.Metadata().Timestamp, packet.Metadata().Timestamp.UTC(), packet.Metadata().Timestamp)
			assembler.AssembleWithTimestamp(packet.NetworkLayer().NetworkFlow(), tcp, packet.Metadata().Timestamp)

		case <-ticker:
			// Every minute, flush connections that haven't seen activity in the past 2 minutes.
			assembler.FlushOlderThan(time.Now().Add(time.Minute * -2))
		}
	}
}
示例#17
0
文件: listener.go 项目: buger/gor
func (t *Listener) readPcapFile() {
	if handle, err := pcap.OpenOffline(t.addr); err != nil {
		log.Fatal(err)
	} else {
		t.readyCh <- true
		packetSource := gopacket.NewPacketSource(handle, handle.LinkType())

		for {
			packet, err := packetSource.NextPacket()
			if err == io.EOF {
				break
			} else if err != nil {
				log.Println("Error:", err)
				continue
			}

			var addr, data []byte

			if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
				tcp, _ := tcpLayer.(*layers.TCP)
				data = append(tcp.LayerContents(), tcp.LayerPayload()...)

				if tcp.SrcPort >= 32768 && tcp.SrcPort <= 61000 {
					copy(data[0:2], []byte{0, 0})
					copy(data[2:4], []byte{0, 1})
				} else {
					copy(data[0:2], []byte{0, 1})
					copy(data[2:4], []byte{0, 0})
				}
			} else {
				continue
			}

			if ipLayer := packet.Layer(layers.LayerTypeIPv4); ipLayer != nil {
				ip, _ := ipLayer.(*layers.IPv4)
				addr = ip.SrcIP
			} else if ipLayer = packet.Layer(layers.LayerTypeIPv6); ipLayer != nil {
				ip, _ := ipLayer.(*layers.IPv6)
				addr = ip.SrcIP
			} else {
				// log.Println("Can't find IP layer", packet)
				continue
			}

			dataOffset := (data[12] & 0xF0) >> 4
			isFIN := data[13]&0x01 != 0

			// We need only packets with data inside
			// Check that the buffer is larger than the size of the TCP header
			if len(data) <= int(dataOffset*4) && !isFIN {
				continue
			}

			t.packetsChan <- t.buildPacket(addr, data, packet.Metadata().Timestamp)
		}
	}
}
示例#18
0
func getHandle(which string) *pcap.Handle {
	var pcapFile string = "data/" + which + ".pcap"

	handle, err := pcap.OpenOffline(pcapFile)
	if err != nil {
		return nil
	}

	return handle
}
示例#19
0
//TODO obviously not a main function, rename it to the caller
func parseFile(fileName string) list.List {
	connections := list.List{}
	if handle, err := pcap.OpenOffline(fileName); err != nil {
		panic(err)
	} else {
		packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
		processPacketsChan(packetSource.Packets(), &connections)
	}
	return connections
}
示例#20
0
/*
Utility functions

*/
func getPacketData(which string) *gopacket.PacketSource {
	var pcapFile string = "data/" + which + ".pcap"

	handle, err := pcap.OpenOffline(pcapFile)
	if err != nil {
		return nil
	}

	return gopacket.NewPacketSource(handle, handle.LinkType())
}
示例#21
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.Parse()
	logger := log.New(os.Stderr, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)

	pcap, err := pcap.OpenOffline(*pcapFile)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error opening pcap file:", err)
		os.Exit(1)
	}
	h := mongocaputils.NewPacketHandler(pcap)
	m := mongocaputils.NewMongoOpStream(*packetBufSize)

	ch := make(chan struct{})
	go func() {
		defer close(ch)
		for op := range m.Ops {
			// TODO: add other op types
			if opQuery, ok := op.Op.(*mongoproto.OpQuery); ok {
				fbOp := map[string]interface{}{}
				fbOp["ns"] = opQuery.FullCollectionName
				fbOp["ntoskip"] = opQuery.NumberToSkip
				fbOp["ntoreturn"] = opQuery.NumberToReturn
				fbOp["ts"] = json.Date(op.Seen.Unix())
				query, err := rawBSONToJSON(opQuery.Query)
				if err != nil {
					logger.Println(err)
					if !*continueOnError {
						os.Exit(1)
					}
				}
				if strings.HasSuffix(opQuery.FullCollectionName, ".$cmd") {
					fbOp["op"] = "command"
					fbOp["command"] = query
				} else {
					fbOp["op"] = "query"
					fbOp["query"] = query
				}
				fbOpStr, err := json.Marshal(fbOp)
				if err != nil {
					logger.Println(err)
					if !*continueOnError {
						os.Exit(1)
					}
				}
				fmt.Println(string(fbOpStr))
			}
		}
	}()

	if err := h.Handle(m, -1); err != nil {
		fmt.Fprintln(os.Stderr, "pcap_converter: error handling packet stream:", err)
	}
	<-ch
}
示例#22
0
文件: popcorn.go 项目: torz/popcorn
func main() {
	handle, err := pcap.OpenOffline("capture/http.pcap")
	if err != nil {
		panic(err)
	}

	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		handlePacket(packet) // Do something with a packet here.
	}
}
示例#23
0
文件: efhsim.go 项目: ikravets/ev
func (s *EfhSim) AnalyzeInput() (err error) {
	defer errs.PassE(&err)
	handle, err := pcap.OpenOffline(s.inputFileName)
	errs.CheckE(err)
	defer handle.Close()
	pp := processor.NewProcessor()
	pp.LimitPacketNumber(s.inputPacketLimit)
	pp.SetObtainer(handle)
	pp.SetHandler(s)
	errs.CheckE(pp.ProcessAll())
	return
}
示例#24
0
文件: listener.go 项目: yaoshipu/gor
func (t *Listener) readPcapFile() {
	if handle, err := pcap.OpenOffline(t.addr); err != nil {
		log.Fatal(err)
	} else {
		t.readyCh <- true
		packetSource := gopacket.NewPacketSource(handle, handle.LinkType())

		for {
			packet, err := packetSource.NextPacket()
			if err == io.EOF {
				break
			} else if err != nil {
				log.Println("Error:", err)
				continue
			}

			var addr, data []byte

			if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
				tcp, _ := tcpLayer.(*layers.TCP)
				data = append(tcp.LayerContents(), tcp.LayerPayload()...)
				copy(data[2:4], []byte{0, 1})
			} else {
				continue
			}

			if ipLayer := packet.Layer(layers.LayerTypeIPv4); ipLayer != nil {
				ip, _ := ipLayer.(*layers.IPv4)
				addr = ip.SrcIP
			} else if ipLayer = packet.Layer(layers.LayerTypeIPv6); ipLayer != nil {
				ip, _ := ipLayer.(*layers.IPv6)
				addr = ip.SrcIP
			} else {
				// log.Println("Can't find IP layer", packet)
				continue
			}

			dataOffset := (data[12] & 0xF0) >> 4

			// We need only packets with data inside
			// Check that the buffer is larger than the size of the TCP header
			if len(data) <= int(dataOffset*4) {
				continue
			}

			newBuf := make([]byte, len(data)+16)
			copy(newBuf[:16], addr)
			copy(newBuf[16:], data)

			t.packetsChan <- newBuf
		}
	}
}
func main() {
	defer util.Run()()
	var handle *pcap.Handle
	var err error
	signal.Notify(sigs, syscall.SIGHUP)
	go startWebServer()
	go sighandler()
	flag.Parse()
	go printDebugInfo()
	if fname != "" {
		if handle, err = pcap.OpenOffline(fname); err != nil {
			log.Fatal("PCAP OpenOffline error:", err)
		}
	} else {
		// This is a little complicated because we want to allow all possible options
		// for creating the packet capture handle... instead of all this you can
		// just call pcap.OpenLive if you want a simple handle.
		inactive, err := pcap.NewInactiveHandle(iface)
		if err != nil {
			log.Fatal("could not create: %v", err)
		}
		defer inactive.CleanUp()
		if err = inactive.SetSnapLen(snaplen); err != nil {
			log.Fatal("could not set snap length: %v", err)
		} else if err = inactive.SetPromisc(true); err != nil {
			log.Fatal("could not set promisc mode: %v", err)
		} else if err = inactive.SetTimeout(time.Second); err != nil {
			log.Fatal("could not set timeout: %v", err)
		}
		if tstype != "" {
			if t, err := pcap.TimestampSourceFromString(tstype); err != nil {
				log.Fatalf("Supported timestamp types: %v", inactive.SupportedTimestamps())
			} else if err := inactive.SetTimestampSource(t); err != nil {
				log.Fatalf("Supported timestamp types: %v", inactive.SupportedTimestamps())
			}
		}
		if handle, err = inactive.Activate(); err != nil {
			log.Fatal("PCAP Activate error:", err)
		}
		defer handle.Close()
		if len(flag.Args()) > 0 {
			bpffilter := strings.Join(flag.Args(), " ")
			fmt.Fprintf(os.Stderr, "Using BPF filter %q\n", bpffilter)
			if err = handle.SetBPFFilter(bpffilter); err != nil {
				log.Fatal("BPF filter error:", err)
			}
		}
	}
	for {
		process(handle)
	}
}
示例#26
0
func main() {
	flag.Parse()
	args := flag.Args()
	if flag.NArg() != 1 {
		usage()
	}

	log.Printf("layers: processing file '%s'\n", args[0])
	if len(args[0]) <= 0 {
		log.Printf("layers: invalid args[0] in: '-r %s'\n", args[0])
	}

	handle, err := pcap.OpenOffline(args[0])
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	packets := []gopacket.Packet{}
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		packets = append(packets, packet)
	}

	for i, p := range packets {

		// see "type PacketMetadata struct" and "type CaptureInfo struct"
		// in github.com/google/gopacket/packet.go:
		log.Printf("\n%v. packet=%v:\n", i+1, p.Metadata().CaptureInfo.Timestamp.UTC())
		// log.Printf("\n%v. packet:\n%#v\n", i+1, p)
		// log.Printf("file.expectedLayers=%T=%#v\n", file.expectedLayers, file.expectedLayers)
		// see issue: https://github.com/google/gopacket/issues/175
		// log.Printf(p.Dump()) // fails in Go 1.6, see https://golang.org/doc/go1.6#reflect
		// log.Printf(p.String()) // fails in Go 1.6, see https://golang.org/doc/go1.6#reflect

		// Iterate over all layers, printing out each layer type
		log.Println("All packet layers:")
		for _, layer := range p.Layers() {
			log.Println("- ", layer.LayerType())
		}

		// for _, layertype := range file.expectedLayers {
		//  if p.Layer(layertype) == nil {
		//    log.Fatal("Packet", i, "has no layer type\n%s", layertype, p.Dump())
		//  }
		// }

	} // for range packets

	log.Printf("packets count=%v\n", len(packets))
}
示例#27
0
文件: scanner.go 项目: gennady1/DNA
func read_pcap_file(pcap_file string) {
	fmt.Printf("\t-- Reading PCAP file: %s --", pcap_file)
	if handle, err := pcap.OpenOffline(pcap_file); err != nil {
		fmt.Println("Error opening file: " + pcap_file + "\n")
		panic(err)
	} else {
		packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
		for packet := range packetSource.Packets() {

			process_gopacket(packet)
			// fmt.Println(packet.Metadata().CaptureInfo)
		}
	}
}
示例#28
0
func main() {
	// Open file instead of device
	handle, err = pcap.OpenOffline(pcapFile)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	// Loop through packets in file
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		fmt.Println(packet)
	}
}
示例#29
0
func main() {
	// Open pcap file
	handle, err = pcap.OpenOffline("test.pcap")
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	// Process packets
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		fmt.Println(packet)
	}
}
示例#30
0
func main() {
	file := flag.String("file", "", "A file to parse")
	dev := flag.String("dev", "", "A dev to sniff")

	flag.Parse()

	if (*file == "" && *dev == "") || (*file != "" && *dev != "") {
		flag.Usage()
		os.Exit(1)
	}

	var handle *pcap.Handle
	var err error

	// Open the pcap file or device.
	if *file != "" {
		if handle, err = pcap.OpenOffline(*file); err != nil {
			panic(err)
		}
	} else {
		if handle, err = pcap.OpenLive(*dev, 8196, true, pcap.BlockForever); err != nil {
			panic(err)
		}
	}

	count := 0
	bars := []string{"-", "\\", "|", "/"}

	sess := qilib.NewSession(qilib.Config{
		Handle: handle,
		Progress: func(pkt gopacket.Packet) {
			fmt.Printf("\r%v ", bars[count%len(bars)])
			count++
		},
		Warning: func(pkt gopacket.Packet, diff qilib.Diff) {
			fmt.Printf("\n%v %v\n<A>\n%s\n</A>\n<B>\n%s\n</B>\n", diff.ID, diff.Seq, diff.A, diff.B)
		},
		Unparseable: func(pkt gopacket.Packet) {
			fmt.Printf("\nUnparseable packet\n%v\n", pkt)
		},
	})
	defer sess.Clean()

	if err := sess.Run(); err != nil {
		log.Fatal(err)
	}
	fmt.Println()

}