How can I re-filter a scapy packet using BPF?

987 views Asked by At

I'm writing a program that needs to re-filter the packets captured by sniff().I want to apply BPF filer to each packet and if it matches, return true, else return false.

Could any one give me some hints?Thanks!

1

There are 1 answers

0
Pierre On BEST ANSWER

For the record, this is my answer on the issue you have opened:

You don't need a BytesIO object, since the offline parameter of sniff() can accept a PacketList or a single Packet.

You can do:

pkts=sniff(count=10)
pkts_icmp = sniff(offline=pkts, filter='icmp')

The data is passed to a tcpdump process through its standard input, so it won't touch your hard drive, unless you're using MacOS X (but that's a tcpdump / MacOS X limitation, Scapy cannot do better here).

If you want a per packet test, you can do:

pkts = sniff(count=10)
for pkt in pkts:
    if sniff(offline=pkt, filter='icmp'):
        print 'match!'

Please not that this will fork a tcpdump process for each packet, which is probably not ideal.

As a side note, if your test is that simple, you can also use a Scapy test instead (it's not strictly equivalent though, but can be helpful in some situations and will not fork a process for each processed packet):

pkts = sniff(count=10)
for pkt in pkts:
    if ICMP in pkt:
        print 'match!'