Skip to content

Commit

Permalink
add new flag: -c
Browse files Browse the repository at this point in the history
  • Loading branch information
mozillazg committed Apr 27, 2024
1 parent e750e34 commit 1437442
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
1 change: 1 addition & 0 deletions cmd/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ type Options struct {
listInterfaces bool
version bool
print bool
maxPacketCount uint
}

func (o Options) WritePath() string {
Expand Down
6 changes: 5 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func init() {
"Print the ptcpdump and libpcap version strings and exit")
rootCmd.Flags().BoolVar(&opts.print, "print", false,
"Print parsed packet output, even if the raw packets are being saved to a file with the -w flag")
rootCmd.Flags().UintVarP(&opts.maxPacketCount, "receive-count", "c", 0, "Exit after receiving count packets")
}

func Execute() error {
Expand Down Expand Up @@ -104,7 +105,10 @@ func run(cmd *cobra.Command, args []string) error {
execConsumer := consumer.NewExecEventConsumer(pcache)
go execConsumer.Start(ctx, execEventReader)
packetConsumer := consumer.NewPacketEventConsumer(writers, devices)
go packetConsumer.Start(ctx, packetEventReader)
go func() {
packetConsumer.Start(ctx, packetEventReader, opts.maxPacketCount)
stop()
}()

runtime.Gosched()

Expand Down
9 changes: 8 additions & 1 deletion internal/consumer/net.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ func NewPacketEventConsumer(writers []writer.PacketWriter, devices map[int]dev.D
}
}

func (c *PacketEventConsumer) Start(ctx context.Context, reader *perf.Reader) {
func (c *PacketEventConsumer) Start(ctx context.Context, reader *perf.Reader, maxPacketCount uint) {
var n uint
for {
select {
case <-ctx.Done():
Expand All @@ -43,6 +44,12 @@ func (c *PacketEventConsumer) Start(ctx context.Context, reader *perf.Reader) {
log.Printf("[PacketEventConsumer] lost samples: %d", record.LostSamples)
}
c.parsePacketEvent(record.RawSample)

n++
if maxPacketCount > 0 && n == maxPacketCount {
log.Printf("%d packets captured", n)
break
}
}
}

Expand Down

0 comments on commit 1437442

Please sign in to comment.