How can I filter a pcap file by specific protocol using python?
Question: I have some pcap files and I want to filter by protocol, i.e., if I want to
filter by HTTP protocol, anything but HTTP packets will remain in the pcap
file.

There is a tool called [openDPI](http://www.opendpi.org/), and it's perfect
for what I need, but there is no wrapper for python language.

Does anyone knows any python modules that can do what I need?

Thanks

**Edit 1:**

HTTP filtering was just an example, there is a lot of protocols that I want to
filter.

**Edit 2:**

I tried Scapy, but I don't figure how to filter correctly. The filter only
accepts Berkeley Packet Filter expression, i.e., I can't apply a msn, or HTTP,
or another specific filter from upper layer. Can anyone help me?


Answer: I know this is a super-old question, but I just ran across it thought I'd
provide **_my_** answer. This is a problem I've encountered several times over
the years, and I keep finding myself falling back to
[dpkt](http://code.google.com/p/dpkt/). Originally from the very capable
[dugsong](http://monkey.org/~dugsong/), dpkt is primarily a packet
creation/parsing library. I get the sense the pcap parsing was an
afterthought, but it turns out to be a very useful one, because parsing pcaps,
IP, TCP and and TCP headers is straightforward. It's parsing all the higher-
level protocols that becomes the time sink! (I wrote my own python pcap
parsing library before finding dpkt)

The documentation on using the pcap parsing functionality is a little thin.
Here's an example from my files:

    
    
    import socket
    import dpkt
    import sys
    pcapReader = dpkt.pcap.Reader(file(sys.argv[1], "rb"))
    for ts, data in pcapReader:
        ether = dpkt.ethernet.Ethernet(data)
        if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
        ip = ether.data
        src = socket.inet_ntoa(ip.src)
        dst = socket.inet_ntoa(ip.dst)
        print "%s -> %s" % (src, dst)
    

Hope this helps the next guy to run across this post!

