当前位置: 首页>>代码示例>>Golang>>正文


Golang pcap.Handle类代码示例

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


在下文中一共展示了Handle类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: writePacket

func writePacket(handle *pcap.Handle, buf []byte) error {
	if err := handle.WritePacketData(buf); err != nil {
		log.Printf("Failed to send packet: %s\n", err)
		return err
	}
	return nil
}
开发者ID:jesseward,项目名称:gopacket,代码行数:7,代码来源:main.go

示例2: 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

示例3: 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

示例4: sniff

func (p *Pcap) sniff(readHandle *pcap.Handle, consumer BridgeConsumer) {
	dec := NewEthernetDecoder()

	for {
		pkt, _, err := readHandle.ZeroCopyReadPacketData()
		if err == pcap.NextErrorTimeoutExpired {
			continue
		}

		checkFatal(err)
		dec.DecodeLayers(pkt)
		if len(dec.decoded) == 0 {
			continue
		}

		if fop := consumer(dec.PacketKey()); !fop.Discards() {
			// We are handing over the frame to
			// forwarders, so we need to make a copy of it
			// in order to prevent the next capture from
			// overwriting the data
			pktLen := len(pkt)
			pktCopy := make([]byte, pktLen, pktLen)
			copy(pktCopy, pkt)

			fop.Process(pktCopy, dec, false)
		}
	}
}
开发者ID:brb,项目名称:weave,代码行数:28,代码来源:pcap.go

示例5: writeARP

// writeARP writes an ARP request for each address on our local network to the
// pcap handle.
func writeARP(handle *pcap.Handle, iface *net.Interface, addr *net.IPNet) error {
	// Set up all the layers' fields we can.
	eth := layers.Ethernet{
		SrcMAC:       iface.HardwareAddr,
		DstMAC:       net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
		EthernetType: layers.EthernetTypeARP,
	}
	arp := layers.ARP{
		AddrType:          layers.LinkTypeEthernet,
		Protocol:          layers.EthernetTypeIPv4,
		HwAddressSize:     6,
		ProtAddressSize:   4,
		Operation:         layers.ARPRequest,
		SourceHwAddress:   []byte(iface.HardwareAddr),
		SourceProtAddress: []byte(addr.IP),
		DstHwAddress:      []byte{0, 0, 0, 0, 0, 0},
	}
	// Set up buffer and options for serialization.
	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{
		FixLengths:       true,
		ComputeChecksums: true,
	}
	// Send one packet for every address.
	for _, ip := range ips(addr) {
		arp.DstProtAddress = []byte(ip)
		gopacket.SerializeLayers(buf, opts, &eth, &arp)
		if err := handle.WritePacketData(buf.Bytes()); err != nil {
			return err
		}
	}
	return nil
}
开发者ID:CNDonny,项目名称:scope,代码行数:35,代码来源:arpscan.go

示例6: 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

示例7: 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

示例8: Sniff

// Sniff captures probe requests using the given handle and writes them to a channel.
func Sniff(handle *pcap.Handle) <-chan wifitracker.Request {
	out := make(chan wifitracker.Request, 0)

	go func() {
		defer close(out)
		packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
		for packet := range packetSource.Packets() {
			handlePacket(packet, out)
		}
	}()
	return out
}
开发者ID:durl,项目名称:go-wifi-tracker,代码行数:13,代码来源:sniffer.go

示例9: main

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)
	}
}
开发者ID:fipar,项目名称:ognom-toolkit,代码行数:52,代码来源:mongo-response-time-exporter.go

示例10: ExtractPGPackets

func ExtractPGPackets(handle *pcap.Handle) (*metrics.QueryMetrics, []*ResponsePacket) {
	combinedQueryMetrics := metrics.NewQueryMetrics()
	responses := []*ResponsePacket{}
	// Sorts packets into queries or responses
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	var raw string
	for {
		packet, err := packetSource.NextPacket()
		if err == io.EOF {
			break
		} else if err != nil {
			fmt.Println("Error: ", err)
			continue
		}

		ipLayer := packet.Layer(layers.LayerTypeIPv4)
		if ipLayer == nil {
			continue
		}
		ip, _ := ipLayer.(*layers.IPv4)

		tcpLayer := packet.Layer(layers.LayerTypeTCP)
		if tcpLayer == nil {
			continue
		}
		tcp, _ := tcpLayer.(*layers.TCP)

		// If the destination port is 5432...
		if tcp.DstPort == 5432 {
			// And the packet payload starts with P...
			raw = fmt.Sprintf("%s", tcp.Payload)
			if strings.HasPrefix(raw, "P") {
				// It is a (Parse) packet that contains a Query
				combinedQueryMetrics.Add(
					metrics.New(
						NormalizeQuery(raw),
						1,
						ip.SrcIP,
						tcp.Seq,
					),
				)
			}
		} else if tcp.SrcPort == 5432 && tcp.ACK {
			responses = append(responses, &ResponsePacket{
				DstIP: ip.DstIP,
				Ack:   tcp.Ack,
				Size:  uint64(len(tcp.Payload)),
			})
		}
	}
	return combinedQueryMetrics, responses
}
开发者ID:procore,项目名称:pgnetdetective,代码行数:52,代码来源:processing.go

示例11: setDeviceFilter

// set packet capture filter, by ip and port
func setDeviceFilter(handle *pcap.Handle, filterIP string, filterPort uint16) {
	var bpfFilter = "tcp"
	if filterPort != 0 {
		bpfFilter += " port " + strconv.Itoa(int(filterPort))
	}
	if filterIP != "" {
		bpfFilter += " ip host " + filterIP
	}
	var err = handle.SetBPFFilter(bpfFilter)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Set capture filter failed, ", err)
	}
}
开发者ID:caoqianli,项目名称:httpcap,代码行数:14,代码来源:main.go

示例12: main

func main() {
	flag.Parse()

	for _, arg := range flag.Args() {
		log.Println("reading", arg)

		var r *pcap.Handle
		var err error
		if r, err = pcap.OpenOffline(arg); err != nil {
			log.Printf("error reading %s: %v\n", arg, err)
			continue
		}

		s := session.New()
		d := netflow.NewDecoder(s)

		packetSource := gopacket.NewPacketSource(r, r.LinkType())
		for packet := range packetSource.Packets() {
			log.Println("packet:", packet)

			m, err := d.Read(bytes.NewBuffer(packet.TransportLayer().LayerPayload()))
			if err != nil {
				log.Println("decoder error:", err)
				continue
			}

			switch p := m.(type) {
			case *netflow1.Packet:
				netflow1.Dump(p)

			case *netflow5.Packet:
				netflow5.Dump(p)

			case *netflow6.Packet:
				netflow6.Dump(p)

			case *netflow7.Packet:
				netflow7.Dump(p)

			case *netflow9.Packet:
				netflow9.Dump(p)

			case *ipfix.Message:
				ipfix.Dump(p)
			}
		}
	}
}
开发者ID:tehmaze,项目名称:netflow,代码行数:48,代码来源:main.go

示例13: main

func main() {
	flag.Parse()

	filter := strings.Join(flag.Args(), " ")

	if device == NO_DEVICE && offlineFile == NO_OFFLINE_FILE {
		flag.Usage()
		os.Exit(1)
	}

	var (
		handle *pcap.Handle
		err    error
	)

	if hasFile(offlineFile) {
		fmt.Printf("Reading packet from %s:\n", offlineFile)
		handle, err = pcap.OpenOffline(offlineFile)
	} else {
		fmt.Printf("Reading packet from %s:\n", device)
		handle, err = pcap.OpenLive(
			device,
			PACKET_SAMPLE_SIZE,
			true,
			pcap.BlockForever,
		)
	}
	if err != nil {
		panic(err)
	}

	fmt.Printf("Applying filter: %s\n", filter)
	if err = handle.SetBPFFilter(filter); err != nil {
		panic(err)
	}

	for {
		packet, ci, err := handle.ReadPacketData()
		if err == io.EOF {
			break
		}
		if err != nil {
			panic(err)
		}
		go handlePacket(packet, ci)
	}
}
开发者ID:migsbeast,项目名称:homework,代码行数:47,代码来源:sniffer.go

示例14: main

func main() {
	defer util.Run()()
	var handle *pcap.Handle
	var err error
	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(*promisc); 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)
			}
		}
	}
	// https://github.com/google/gopacket/blob/master/dumpcommand/tcpdump.go
	dumpcommand.Run(handle)
}
开发者ID:hb9cwp,项目名称:rsTestGopacket,代码行数:46,代码来源:pcapDump.go

示例15: sendPacket

func sendPacket(handle *pcap.Handle, sMac, dMac net.HardwareAddr, sIp, dIp net.IP, sPort, dPort layers.TCPPort, IpId uint16, IpTtl uint8, TcpSeq, ack uint32, WindowsSize uint16, data []byte) error {
	eth := layers.Ethernet{
		SrcMAC:       sMac,
		DstMAC:       dMac,
		EthernetType: layers.EthernetTypeIPv4,
	}
	ip4 := layers.IPv4{
		SrcIP:    sIp,
		DstIP:    dIp,
		Id:       IpId,
		Flags:    layers.IPv4DontFragment,
		Version:  4,
		TTL:      IpTtl,
		Protocol: layers.IPProtocolTCP,
	}
	tcp := layers.TCP{
		SrcPort: sPort,
		DstPort: dPort,
		Seq:     TcpSeq,
		ACK:     true,
		Ack:     ack,
		Window:  WindowsSize,
		PSH:     true, // 立刻处理
	}

	if len(data) == 0 {
		tcp.RST = true
	}

	tcp.SetNetworkLayerForChecksum(&ip4)

	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{
		FixLengths:       true,
		ComputeChecksums: true,
	}

	payload := gopacket.Payload(data)

	if err := gopacket.SerializeLayers(buf, opts, &eth, &ip4, &tcp, payload); err != nil {
		return err
	}

	return handle.WritePacketData(buf.Bytes())
}
开发者ID:jannson,项目名称:ProxyClient,代码行数:45,代码来源:ttl.go


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