• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang pcap.OpenOffline函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/google/gopacket/pcap.OpenOffline函数的典型用法代码示例。如果您正苦于以下问题:Golang OpenOffline函数的具体用法?Golang OpenOffline怎么用?Golang OpenOffline使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了OpenOffline函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: readPcapFile

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)
		}
	}
}
开发者ID:buger,项目名称:gor,代码行数:57,代码来源:listener.go


示例17: getHandle

func getHandle(which string) *pcap.Handle {
	var pcapFile string = "data/" + which + ".pcap"

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

	return handle
}
开发者ID:Phillipmartin,项目名称:gopassivedns,代码行数:10,代码来源:main_test.go


示例18: parseFile

//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
}
开发者ID:rahulsom,项目名称:tlsdr,代码行数:11,代码来源:ParserUtil.go


示例19: getPacketData

/*
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())
}
开发者ID:Phillipmartin,项目名称:gopassivedns,代码行数:14,代码来源:main_test.go


示例20: main

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
}
开发者ID:bradparks,项目名称:flashback,代码行数:55,代码来源:main.go



注:本文中的github.com/google/gopacket/pcap.OpenOffline函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang pcap.Handle类代码示例发布时间:2022-05-23
下一篇:
Golang pcap.OpenLive函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap