I created a packet from raw bytes using gopacket and write these packets to a pcap file.
I created a UDP packet from raw bytes as below.
package main
import (
"fmt"
"net"
"log"
"os"
"time"
//"encoding/hex"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"github.com/google/gopacket/pcapgo"
)
var (
device string = "eth0"
snapshot_len int32 = 65535
promiscuous bool = false
err error
timeout time.Duration = 30 * time.Second
handle *pcap.Handle
buffer gopacket.SerializeBuffer
options gopacket.SerializeOptions
)
func main() {
ethernetLayer := &layers.Ethernet{
SrcMAC: net.HardwareAddr{0xFF, 0xAA, 0xFA, 0xAA, 0xFF, 0xAA},
DstMAC: net.HardwareAddr{0xBD, 0xBD, 0xBD, 0xBD, 0xBD, 0xBD},
}
ipLayer := &layers.IPv4{
SrcIP: net.IP{127,0,0,1},
DstIP: net.IP{8,8,8,8},
}
udpLayer := &layers.UDP{
SrcPort: 51190,
DstPort: 4789,
}
rawBytes := []byte{10, 20, 30}
buffer = gopacket.NewSerializeBuffer()
gopacket.SerializeLayers(buffer, options,
ethernetLayer,
ipLayer,
udpLayer,
gopacket.Payload(rawBytes),
)
outgoingPacket := buffer.Bytes()
fmt.Println(outgoingPacket)
ethpacket := gopacket.NewPacket(outgoingPacket,
layers.LayerTypeEthernet,
gopacket.Default )
How do I write this packet to a pcap file.
The example I found on this link, shows how to read packets from a device and write to a pcap file, but does not give an example of write to a pcap file when I have a bunch of packets.
https://www.devdungeon.com/content/packet-capture-injection-and-analysis-gopacket#write-pcap-file
Please help me proceed on this.
Since, I already have my packet framed, I modified the write pcap code as below.
f, err := os.Create("temp.pcap")
if err != nil {
log.Fatal(err)
os.Exit(1)
}
defer f.Close()
w := pcapgo.NewWriter(f)
w.WriteFileHeader(uint32(snapshot_len), layers.LinkTypeEthernet)
err = w.WritePacket(ethpacket.Metadata().CaptureInfo, ethpacket.Data())
if err != nil {
log.Fatal(err)
}
After running the program, this is the error its throwing. The pcap file shows 24 bytes, which has only the pcap file header.
go run create_pcap.go
2021/08/24 06:34:22 capture length 0 does not match data length 60
ls -l
-rw-r--r-- 1 root root 24 Aug 24 06:34 temp.pcap