在抓到包时 将其添加到一个slice中
var PkgInfos []gopacket.Packet
for packet := range packetSource.Packets() {
//packet:=<-packetSource.Packets()
p := anlysePacket(packet)
p.No = No
PkgInfos=append(PkgInfos,packet)
No++
list.Append(p.formatePkgListInfo())
//fmt.Println( packet.Data())
}
pcap.go
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"
)
var (
deviceName string = "eth0"
snapshotLen int32 = 1024
promiscuous bool = false
err error
timeout time.Duration = -1 * time.Second
handle *pcap.Handle
packetCount int = 0
)
func openPcap(pcapFile string) {
// Open file instead of device
handle, err = pcap.OpenOffline(pcapFile)
if err != nil { log.Fatal(err) }
defer handle.Close()
// Loop through packets in file
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range packetSource.Packets() {
fmt.Println(packet)
}
}
func SaveAsPcap(PkgInfos []gopacket.Packet) {
// Open output pcap file and write header
f, _ := os.Create("test.pcap")
w := pcapgo.NewWriter(f)
w.WriteFileHeader(uint32(snapshotLen), layers.LinkTypeEthernet)
defer f.Close()
// Open the device for capturing
//handle, err = pcap.OpenLive(deviceName, snapshotLen, promiscuous, timeout)
if err != nil {
fmt.Printf("Error opening device %s: %v", deviceName, err)
os.Exit(1)
}
defer handle.Close()
// Start processing packets
//packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for _,packet:=range PkgInfos {
// Process packet here
fmt.Println(packet)
w.WritePacket(packet.Metadata().CaptureInfo, packet.Data())
packetCount++
// Only capture 100 and then stop
if packetCount > 100 {
break
}
}
}
注意文件名不能带:和/等符号
然后绑定到窗口菜单上的保存按钮 就可以实现保存了