Exemplo n.º 1
0
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
}
Exemplo n.º 2
0
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)
	}
}
Exemplo n.º 3
0
Arquivo: pcap.go Projeto: adoyee/probe
func doReadPacket(handle *pcap.Handle) {
	var err error
	handle.SetBPFFilter(filter)
	if err != nil {
		log.Fatal(err)
	}
	for {
		data, ci, err := handle.ReadPacketData()

		switch {
		case err == io.EOF:
			return
		case err != nil:
			log.Println(err)
		default:
			packet := gopacket.NewPacket(data, layers.LayerTypeEthernet, gopacket.NoCopy)
			incomePacket := incomePacket{packet: packet, ci: &ci}
			switchPacket(incomePacket)
		}
	}

}