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


Golang pcap.OpenLive函数代码示例

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


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

示例1: tryCapture

func tryCapture(iface net.Interface) error {
	if iface.Name[:2] == "lo" {
		return fmt.Errorf("skipping loopback")
	}
	var h *pcap.Handle
	var err error
	switch *mode {
	case "basic":
		h, err = pcap.OpenLive(iface.Name, 65536, false, time.Second*3)
		if err != nil {
			return fmt.Errorf("openlive: %v", err)
		}
		defer h.Close()
	case "filtered":
		h, err = pcap.OpenLive(iface.Name, 65536, false, time.Second*3)
		if err != nil {
			return fmt.Errorf("openlive: %v", err)
		}
		defer h.Close()
		if err := h.SetBPFFilter("port 80 or port 443"); err != nil {
			return fmt.Errorf("setbpf: %v", err)
		}
	case "timestamp":
		u, err := pcap.NewInactiveHandle(iface.Name)
		if err != nil {
			return err
		}
		defer u.CleanUp()
		if err = u.SetSnapLen(65536); err != nil {
			return err
		} else if err = u.SetPromisc(false); err != nil {
			return err
		} else if err = u.SetTimeout(time.Second * 3); err != nil {
			return err
		}
		sources := u.SupportedTimestamps()
		if len(sources) == 0 {
			return fmt.Errorf("no supported timestamp sources")
		} else if err := u.SetTimestampSource(sources[0]); err != nil {
			return fmt.Errorf("settimestampsource(%v): %v", sources[0], err)
		} else if h, err = u.Activate(); err != nil {
			return fmt.Errorf("could not activate: %v", err)
		}
		defer h.Close()
	default:
		panic("Invalid --mode: " + *mode)
	}
	go generatePackets()
	h.ReadPacketData() // Do one dummy read to clear any timeouts.
	data, ci, err := h.ReadPacketData()
	if err != nil {
		return fmt.Errorf("readpacketdata: %v", err)
	}
	log.Printf("Read packet, %v bytes, CI: %+v", len(data), ci)
	return nil
}
开发者ID:hgGeorg,项目名称:mongo,代码行数:56,代码来源:pcap_tester.go

示例2: intiateHandles

/*
   FUNCTION: intiateHandles(iface string)
   RETURNS: Nothing
   ARGUMENTS:
               string iface - the interface to monitor

   ABOUT:
   Intiates all packet capture handles for the client. One for the main system and one for the file thread.
*/
func intiateHandles(iface string) {

	handle, err = pcap.OpenLive(iface, 1600, true, pcap.BlockForever)
	checkError(err)

	err = handle.SetBPFFilter("udp")
	checkError(err)

	fhandle, err = pcap.OpenLive(iface, 1600, true, pcap.BlockForever)
	checkError(err)

	err = fhandle.SetBPFFilter("udp")
	checkError(err)
}
开发者ID:razc411,项目名称:GoBD,代码行数:23,代码来源:server.go

示例3: main

func main() {
	getLocalAddresses()
	log.Print(getFilterString())

	//if handle, err := pcap.OpenOffline("attack3.pcap"); err != nil {
	if handle, err := pcap.OpenLive("any", 512, false, pcap.BlockForever); err != nil {
		panic(err)
	} else if err := handle.SetBPFFilter(getFilterString()); err != nil {
		panic(err)
	} else {
		//var offset time.Duration

		packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
		for packet := range packetSource.Packets() {

			/*
				// delay to simulate actual time span
				if offset == 0 {
					offset = time.Now().Sub(packet.Metadata().Timestamp)
				}

				sleep := packet.Metadata().Timestamp.Add(offset).Sub(time.Now())
				time.Sleep(sleep)
			*/

			handlePacket(packet)
		}
	}
}
开发者ID:twcclan,项目名称:getstatus-limiter,代码行数:29,代码来源:main.go

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

示例5: Open

func (s *PcapSniffer) Open(config *Config) error {
	// Capture settings
	const (
		// Max packet length
		snaplen int32 = 65536
		// Set the interface in promiscuous mode
		promisc bool = true
		// Timeout duration
		flushAfter string = "10s"
		//BPF filter when capturing packets
		filter string = "ip"
	)

	// Open the interface
	flushDuration, err := time.ParseDuration(flushAfter)
	if err != nil {
		return fmt.Errorf("Invalid flush duration: %s", flushAfter)
	}
	handle, err := pcap.OpenLive(*iface, snaplen, promisc, flushDuration/2)
	if err != nil {
		return fmt.Errorf("Error opening pcap handle: %s", err)
	}
	if err := handle.SetBPFFilter(filter); err != nil {
		return fmt.Errorf("Error setting BPF filter: %s", err)
	}
	s.handle = handle

	return nil
}
开发者ID:hb9cwp,项目名称:sniffer,代码行数:29,代码来源:pcap.go

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

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

示例8: openDevice

func openDevice(device string) *pcap.Handle {
	handle, err := pcap.OpenLive(device, 65536, false, pcap.BlockForever)
	if err != nil {
		log.Fatal("Open device", device, "error:", err)
	}
	return handle
}
开发者ID:caoqianli,项目名称:httpcap,代码行数:7,代码来源:main.go

示例9: main

func main() {
	// Open device
	handle, err = pcap.OpenLive(device, snapshot_len, promiscuous, timeout)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	bpfInstructions := []pcap.BPFInstruction{
		{0x20, 0, 0, 0xfffff038}, // ld rand
		{0x54, 0, 0, 0x00000004},
		{0x15, 0, 1, 0x00000004},
		{0x06, 0, 0, 0x0000ffff},
		{0x06, 0, 0, 0000000000},
	}

	err = handle.SetBPFInstructionFilter(bpfInstructions)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Capturing ~4th packet (randomly).")

	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		// Do something with a packet here.
		fmt.Println(packet)
	}

}
开发者ID:breml,项目名称:mygoplayground,代码行数:29,代码来源:filter.go

示例10: Read_RAW_Socket_Data

//----- PCAP read from
func Read_RAW_Socket_Data() {
	fmt.Println("|---------------------------------------------------------------|")
	fmt.Println("|  [scanner] Opening Device (PROMISCUOUS_MODE): " + networkDeviceName + "\t\t|")

	// Open device
	handle, err = pcap.OpenLive(networkDeviceName, snapshot_len, promiscuous, timeout)
	if err != nil {
		fmt.Println("| ----------------=============================-----------------|")
		fmt.Println("| Looks like there is an error getting live network stream. Try |")
		fmt.Println("| running it again with 'sudo' command                          |")
		fmt.Println("| ----------------=============================-----------------|")
		log.Fatal(err)
	}
	defer handle.Close()

	// Set filter
	var filter string = "tcp"
	err = handle.SetBPFFilter(filter)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Only capturing TCP port 80 packets.")

	// Use the handle as a packet source to process all packets
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		process_gopacket(packet)
	}
}
开发者ID:ev46,项目名称:DNA,代码行数:30,代码来源:scanner.go

示例11: Startcollect

func Startcollect(port int, device string, timesignal <-chan time.Time) {
	handle, err = pcap.OpenLive(device, snapshotLen, promiscuous, timeout)
	if err != nil {
		glog.Info(err.Error())
	}

	defer handle.Close()
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	templocalip, err := checkLocalip(device)
	localip = templocalip
	if glog.V(0) {
		glog.Info(localip)
	}
	httpinstancelist = list.New()
	if err != nil {
		glog.Info(err.Error())
	}
A:
	for packet := range packetSource.Packets() {
		select {
		case <-timesignal:
			break A
		default:
			processPacketInfo(packet)

		}

	}
}
开发者ID:wangzhezhe,项目名称:packetagent,代码行数:29,代码来源:packetcollect.go

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

示例13: main

/*
    FUNCTION: main()
    RETURNS: Nothing
    ARGUMENTS: None
    ABOUT:
    Grabs incoming arguments and activates the ARP poisoning thread and the DNS spoofing functionality.
		Also grabs host addresses for use later on and sets global variables.
*/
func main() {

	targetPtr := flag.String("targ", "127.0.0.1", "The address of the host for spoofing.")
	targetMAC := flag.String("targm", "FF:FF:FF:FF:FF:FF", "The target mac address.")
	interfacePtr := flag.String("iface", "eth0", "The interface for the backdoor to monitor for incoming connection, defaults to eth0.")
	gatewayPtr := flag.String("gw", "127.0.0.1", "Sets the gateway to poison.")
	gatewayMAC := flag.String("gwm", "FF:FF:FF:FF:FF:FF", "Sets the gateway MAC address.")

	flag.Parse()

	fmt.Print("Welcome to the DNSMangler!\n")
	handle, err = pcap.OpenLive(*interfacePtr, 1600, false, pcap.BlockForever)
	checkError(err)

	err = handle.SetBPFFilter("dst port 53")
	checkError(err)

	defer handle.Close()

	macAddr, ipAddr = grabAddresses(*interfacePtr)
	target = *targetPtr

	go arpPoison(*targetMAC, *gatewayPtr, *gatewayMAC)
	mangleDNS()
}
开发者ID:razc411,项目名称:DNSMangler,代码行数:33,代码来源:main.go

示例14: main

func main() {
	// Open output pcap file and write header
	dumpFile, _ := os.Create(dumpFilename)
	packetWriter := pcapgo.NewWriter(dumpFile)
	packetWriter.WriteFileHeader(65535, layers.LinkTypeEthernet)
	defer dumpFile.Close()

	// Open device for capturing
	handle, err = pcap.OpenLive(deviceName, snapshotLen, promiscuous, timeout)
	if err != nil {
		log.Fatal("Error opening device %s: %v", deviceName, err)
	}
	defer handle.Close()
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())

	// Start processing packets
	for packet := range packetSource.Packets() {
		fmt.Println(packet)
		packetWriter.WritePacket(packet.Metadata().CaptureInfo, packet.Data())
		packetCount++

		// Only capture 100 packets
		if packetCount > 100 {
			break
		}
	}
}
开发者ID:Rahmadkurniawan,项目名称:2016-talks,代码行数:27,代码来源:writePcapFile.go

示例15: newScanner

// newScanner creates a new scanner for a given destination IP address, using
// router to determine how to route packets to that IP.
func newScanner(ip net.IP, router routing.Router) (*scanner, error) {
	s := &scanner{
		dst: ip,
		opts: gopacket.SerializeOptions{
			FixLengths:       true,
			ComputeChecksums: true,
		},
		buf: gopacket.NewSerializeBuffer(),
	}
	// Figure out the route to the IP.
	iface, gw, src, err := router.Route(ip)
	if err != nil {
		return nil, err
	}
	log.Printf("scanning ip %v with interface %v, gateway %v, src %v", ip, iface.Name, gw, src)
	s.gw, s.src, s.iface = gw, src, iface

	// Open the handle for reading/writing.
	// Note we could very easily add some BPF filtering here to greatly
	// decrease the number of packets we have to look at when getting back
	// scan results.
	handle, err := pcap.OpenLive(iface.Name, 65536, true, pcap.BlockForever)
	if err != nil {
		return nil, err
	}
	s.handle = handle
	return s, nil
}
开发者ID:CNDonny,项目名称:scope,代码行数:30,代码来源:main.go


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