feat(pcap): impl realtime wait() with time offset

This commit is contained in:
Haruue 2024-05-08 19:35:17 +08:00
parent 301f9af3d4
commit 1934c065ec
No known key found for this signature in database
GPG Key ID: F6083B28CBCBC148

View File

@ -19,7 +19,7 @@ var _ PacketIO = (*pcapPacketIO)(nil)
type pcapPacketIO struct { type pcapPacketIO struct {
pcapFile io.ReadCloser pcapFile io.ReadCloser
pcap *pcapgo.Reader pcap *pcapgo.Reader
lastTime *time.Time timeOffset *time.Duration
ioCancel context.CancelFunc ioCancel context.CancelFunc
config PcapPacketIOConfig config PcapPacketIOConfig
@ -45,7 +45,7 @@ func NewPcapPacketIO(config PcapPacketIOConfig) (PacketIO, error) {
return &pcapPacketIO{ return &pcapPacketIO{
pcapFile: pcapFile, pcapFile: pcapFile,
pcap: handle, pcap: handle,
lastTime: nil, timeOffset: nil,
ioCancel: nil, ioCancel: nil,
config: config, config: config,
dialer: &net.Dialer{}, dialer: &net.Dialer{},
@ -101,20 +101,18 @@ func (p *pcapPacketIO) Close() error {
// Intentionally slow down the replay // Intentionally slow down the replay
// In realtime mode, this is to match the timestamps in the capture // In realtime mode, this is to match the timestamps in the capture
func (p *pcapPacketIO) wait(packet gopacket.Packet) error { func (p *pcapPacketIO) wait(packet gopacket.Packet) {
if !p.config.Realtime { if !p.config.Realtime {
return nil return
} }
if p.lastTime == nil { if p.timeOffset == nil {
p.lastTime = &packet.Metadata().Timestamp offset := time.Since(packet.Metadata().Timestamp)
p.timeOffset = &offset
} else { } else {
t := packet.Metadata().Timestamp.Sub(*p.lastTime) t := time.Until(packet.Metadata().Timestamp.Add(*p.timeOffset))
time.Sleep(t) time.Sleep(t)
p.lastTime = &packet.Metadata().Timestamp
} }
return nil
} }
var _ Packet = (*pcapPacket)(nil) var _ Packet = (*pcapPacket)(nil)