Search code examples
pythonpcapscapypacket-capture

Close rdpcap function - Scapy


I have a script that loops through a lot of pcap files. For each pcap file I need to read it and then write some information to a txt file. I'm using the rdcap function from Scapy. Is there anyway to close the pcap file once I'm done reading it? My script has a memory leak and I'm worried this may be the culprit (via leaving many pcap files essentially open)


Solution

  • Inspecting Scapy's source code reveals that the rdpcap function neglects to close the pcap file:

    @conf.commands.register
    def rdpcap(filename, count=-1):
        """Read a pcap file and return a packet list
    count: read only <count> packets"""
        return PcapReader(filename).read_all(count=count)
    

    I suggest you implement your own version of this function as follows:

    def rdpcap_and_close(filename, count=-1):
        """Read a pcap file, return a packet list and close the file
    count: read only <count> packets"""
        pcap_reader = PcapReader(filename)
        packets = pcap_reader.read_all(count=count)
        pcap_reader.close()
        return packets
    

    I've created an issue for this problem here.

    EDIT: The issue has been resolved in this changeset.