refactor(pcap): switch to pcapgo

This commit is contained in:
Haruue 2024-05-08 19:22:17 +08:00
parent 8cab86b924
commit 7456e5907e
No known key found for this signature in database
GPG Key ID: F6083B28CBCBC148

View File

@ -3,19 +3,22 @@ package io
import ( import (
"context" "context"
"hash/crc32" "hash/crc32"
"io"
"net" "net"
"os"
"sort" "sort"
"strings" "strings"
"time" "time"
"github.com/google/gopacket" "github.com/google/gopacket"
"github.com/google/gopacket/pcap" "github.com/google/gopacket/pcapgo"
) )
var _ PacketIO = (*pcapPacketIO)(nil) var _ PacketIO = (*pcapPacketIO)(nil)
type pcapPacketIO struct { type pcapPacketIO struct {
pcap *pcap.Handle pcapFile io.ReadCloser
pcap *pcapgo.Reader
lastTime *time.Time lastTime *time.Time
ioCancel context.CancelFunc ioCancel context.CancelFunc
config PcapPacketIOConfig config PcapPacketIOConfig
@ -29,12 +32,18 @@ type PcapPacketIOConfig struct {
} }
func NewPcapPacketIO(config PcapPacketIOConfig) (PacketIO, error) { func NewPcapPacketIO(config PcapPacketIOConfig) (PacketIO, error) {
handle, err := pcap.OpenOffline(config.PcapFile) pcapFile, err := os.Open(config.PcapFile)
if err != nil {
return nil, err
}
handle, err := pcapgo.NewReader(pcapFile)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &pcapPacketIO{ return &pcapPacketIO{
pcapFile: pcapFile,
pcap: handle, pcap: handle,
lastTime: nil, lastTime: nil,
ioCancel: nil, ioCancel: nil,
@ -87,8 +96,7 @@ func (p *pcapPacketIO) SetCancelFunc(cancelFunc context.CancelFunc) error {
} }
func (p *pcapPacketIO) Close() error { func (p *pcapPacketIO) Close() error {
p.pcap.Close() return p.pcapFile.Close()
return nil
} }
// Intentionally slow down the replay // Intentionally slow down the replay