Capturing network packets with go and writing that in a file
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
1.8 KiB

package main
import (
"fmt"
"log"
"os"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"github.com/google/gopacket/pcapgo"
)
// Handle is a local wrapper around pcap.Handle structure.
type Handle struct {
handle *pcap.Handle
}
func main() {
// find devices and return them
devices := findDevices()
filterExpression := "tcp and port 80"
// try to capture on devices
for _, d := range devices {
fmt.Println("trying:", d.Name)
err := openDeviceForCapture(d.Name, filterExpression)
if err != nil {
fmt.Println(err)
}
}
}
func pcapName(deviceName string) *os.File {
currentTime := time.Now()
fileName := currentTime.Format("2006-01-02 15:04:05") + deviceName + ".pcap"
f, _ := os.Create(fileName)
return f
}
func openDeviceForCapture(deviceName string, filterExpression string) error {
var snapshotLen int32
snapshotLen = 1024
promiscuous := false
var timeout time.Duration
timeout = 30 * time.Second
limit := 0
handle, err := pcap.OpenLive(deviceName, snapshotLen, promiscuous, timeout)
if err != nil {
return err
}
// set filter to handle
if err := handle.SetBPFFilter(filterExpression); err != nil {
return err
}
defer handle.Close()
pcapName := pcapName(deviceName)
w := pcapgo.NewWriter(pcapName)
w.WriteFileHeader(1024, layers.LinkTypeEthernet)
defer pcapName.Close()
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range packetSource.Packets() {
fmt.Println(packet)
w.WritePacket(packet.Metadata().CaptureInfo, packet.Data())
limit++
if limit == 10 {
break
}
}
return nil
}
func findDevices() []pcap.Interface {
devices, err := pcap.FindAllDevs()
if err != nil {
log.Fatal(err)
}
var res []pcap.Interface
for _, d := range devices {
res = append(res, d)
}
return res
}