Ejemplo n.º 1
0
func main() {
	expr := ""

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: %s [ -i interface ] [ -s snaplen ] [ -X ] [ -w file ] [ -h show usage] [ expression ] \n", os.Args[0])
		os.Exit(1)
	}

	flag.Parse()

	if len(flag.Args()) > 0 {
		expr = flag.Arg(0)
	}

	if *help {
		flag.Usage()
	}

	if *device == "" {
		devs, err := pcap.FindAllDevs()
		if err != "" {
			fmt.Fprintln(os.Stderr, "tcpdump: couldn't find any devices:", err)
		}
		if 0 == len(devs) {
			flag.Usage()
		}
		*device = devs[0].Name
	}

	h, err := pcap.OpenLive(*device, int32(*snaplen), true, 500)
	if h == nil {
		fmt.Fprintf(os.Stderr, "tcpdump:", err)
		return
	}
	defer h.Close()

	if expr != "" {
		fmt.Println("tcpdump: setting filter to", expr)
		ferr := h.SetFilter(expr)
		if ferr != nil {
			fmt.Println("tcpdump:", ferr)
		}
	}

	if *ofile != "" {
		dumper, oerr := h.DumpOpen(ofile)
		addHandler(h, dumper)
		if oerr != nil {
			fmt.Fprintln(os.Stderr, "tcpdump: couldn't write to file:", oerr)
		}
		_, lerr := h.PcapLoop(0, dumper)
		if lerr != nil {
			fmt.Fprintln(os.Stderr, "tcpdump: loop error:", lerr, h.Geterror())
		}
		defer h.PcapDumpClose(dumper)
		return
	}

	for pkt, r := h.NextEx(); r >= 0; pkt, r = h.NextEx() {
		if r == 0 {
			// timeout, continue
			continue
		}
		pkt.Decode()
		fmt.Println(pkt)
		if *hexdump {
			Hexdump(pkt)
		}

	}
	fmt.Fprintln(os.Stderr, "tcpdump:", h.Geterror())

}
Ejemplo n.º 2
0
func main() {
	var device *string = flag.String("d", "", "device")
	var file *string = flag.String("r", "", "file")
	var expr *string = flag.String("e", "", "filter expression")

	flag.Parse()

	var h *pcap.Pcap
	var err string

	ifs, err := pcap.FindAllDevs()
	if len(ifs) == 0 {
		fmt.Printf("Warning: no devices found : %s\n", err)
	} else {
		for i := 0; i < len(ifs); i++ {
			fmt.Printf("dev %d: %s (%s)\n", i+1, ifs[i].Name, ifs[i].Description)
		}
	}

	if *device != "" {
		h, err = pcap.OpenLive(*device, 65535, true, 0)
		if h == nil {
			fmt.Printf("OpenLive(%s) failed: %s\n", *device, err)
			return
		}
	} else if *file != "" {
		h, err = pcap.OpenOffline(*file)
		if h == nil {
			fmt.Printf("Openoffline(%s) failed: %s\n", *file, err)
			return
		}
	} else {
		fmt.Printf("usage: pcaptest [-d <device> | -r <file>]\n")
		return
	}

	fmt.Printf("pcap version: %s\n", pcap.Version())

	if *expr != "" {
		fmt.Printf("Setting filter: %s\n", *expr)
		err := h.SetFilter(*expr)
		if err != "" {
			fmt.Printf("Warning: setting filter failed: %s\n", err)
		}
	}

	for pkt := h.Next(); pkt != nil; pkt = h.Next() {
		fmt.Printf("time: %d.%06d (%s) caplen: %d len: %d\nData:",
			int64(pkt.Time.Sec), int64(pkt.Time.Usec),
			time.Unix(int64(pkt.Time.Sec), 0).String(), int64(pkt.Caplen), int64(pkt.Len))
		for i := uint32(0); i < pkt.Caplen; i++ {
			if i%32 == 0 {
				fmt.Printf("\n")
			}
			if 32 <= pkt.Data[i] && pkt.Data[i] <= 126 {
				fmt.Printf("%c", pkt.Data[i])
			} else {
				fmt.Printf(".")
			}
		}
		fmt.Printf("\n\n")
	}

}