當前位置: 首頁>>代碼示例>>Golang>>正文


Golang pcap.OpenOffline函數代碼示例

本文整理匯總了Golang中github.com/google/gopacket/pcap.OpenOffline函數的典型用法代碼示例。如果您正苦於以下問題:Golang OpenOffline函數的具體用法?Golang OpenOffline怎麽用?Golang OpenOffline使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了OpenOffline函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: runTestZone

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

				*/
			}
		}
	}
}
開發者ID:phaxio,項目名稱:filterpcap,代碼行數:33,代碼來源:tester.go

示例2: NewPcapFileSniffer

func NewPcapFileSniffer(filename string) (*PcapHandle, error) {
	pcapFileHandle, err := pcap.OpenOffline(filename)
	pcapHandle := PcapHandle{
		handle: pcapFileHandle,
	}
	return &pcapHandle, err
}
開發者ID:lytics,項目名稱:wherefore,代碼行數:7,代碼來源:libpcap.go

示例3: ParsingFinished

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
}
開發者ID:ikravets,項目名稱:ev,代碼行數:30,代碼來源:benchmark.go

示例4: TestTCP

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())
}
開發者ID:RunxiaWan,項目名稱:oganization,代碼行數:32,代碼來源:main_test.go

示例5: packetSource

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())
}
開發者ID:4lyingli0n,項目名稱:netgraph,代碼行數:29,代碼來源:ng.go

示例6: main

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
}
開發者ID:gabrielrussell,項目名稱:mongocaputils,代碼行數:26,代碼來源:main.go

示例7: TestNgnet

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))
}
開發者ID:4lyingli0n,項目名稱:netgraph,代碼行數:30,代碼來源:ngnet_test.go

示例8: ProcessPackets

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()
	}
}
開發者ID:adamchel,項目名稱:mongo-tcp-replay,代碼行數:27,代碼來源:mongo_packet.go

示例9: init

//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
}
開發者ID:influx6,項目名稱:goproj,代碼行數:29,代碼來源:snifer.go

示例10: pcapInfo

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
}
開發者ID:jesseward,項目名稱:gopacket,代碼行數:35,代碼來源:main.go

示例11: main

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)
		}
	}
}
開發者ID:onvoy,項目名稱:udpreplay,代碼行數:30,代碼來源:main.go

示例12: main

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])
			}
		}
	}
}
開發者ID:moveman,項目名稱:ts,代碼行數:34,代碼來源:main.go

示例13: getOpstream

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
}
開發者ID:gabrielrussell,項目名稱:mongo-tools,代碼行數:35,代碼來源:record.go

示例14: openFile

func openFile(pcapFile string) *pcap.Handle {
	handle, err := pcap.OpenOffline(pcapFile)
	if err != nil {
		log.Fatal("Open file", pcapFile, "error:", err)
	}
	return handle
}
開發者ID:caoqianli,項目名稱:httpcap,代碼行數:7,代碼來源:main.go

示例15: main

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))
		}
	}
}
開發者ID:cleesmith,項目名稱:golang_learning,代碼行數:59,代碼來源:httpassembly.go


注:本文中的github.com/google/gopacket/pcap.OpenOffline函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。