title: Converting raw packets to pcap format and appending to a pcap file
body: <p>I am reading the raw packet data and converting it to Pcap format (have a function for this). I have a list of raw packets (in list format) and I need to read each packet and append it to a pcap file in the pcap format only. I tried using mergecap but it doesn't work. So I tried another thing <code>tail -c +25 file2.pcap &gt;&gt; file1.pcap</code> and it works.</p>
  
  <p>I convert a packet[0] to pcap, store it in a pcap file using the below code, then do similar thing for the remaining packets, and keep on appending the pcap files using the tail command. But it's just an overhead (as I have 10^6 packets).</p>
  
  <p>Here's what I did - </p>
  
  <pre><code>class Pcap:
  
     def __init__( self, filename, link_type=PCAP_DATA_LINK_TYPE ):
        self.pcap_file = open( filename, 'wb' )
        self.pcap_file.write( struct.pack( '@ I H H i I I I ',
                              PCAP_MAGICAL_NUMBER, PCAP_MJ_VERN_NUMBER,
                              PCAP_MI_VERN_NUMBER, PCAP_LOCAL_CORECTIN,
                              PCAP_ACCUR_TIMSTAMP, PCAP_MAX_LENGTH_CAP, link_type ) )
  
     def writelist( self, data ):
        for i in data:
           self.write( i )
        return
  
     def write( self, data ):
        ts_sec, ts_usec = map( int, str( time.time() ).split( '.' ) )
        length = len( data )
        self.pcap_file.write( struct.pack( '@ I I I I', ts_sec,
                                           ts_usec, length, length ) )
        self.pcap_file.write( data )
  
     def close(self):
        self.pcap_file.close()
  
  
  class try:
     def start(self, packets):
        p = Pcap( "PcapData.pcap" )
        p.write( str( packets[0] ) )
        p.pcap_file.flush()
        for packet in packets[1:]:
           p = Pcap( "temp.pcap" )
           p.write( str( packet ) )
           p.pcap_file.flush()
           p.close()
           os.system( "tail -c +25 temp.pcap &gt;&gt; PcapData.pcap" )
        p.close()
  </code></pre>
  
  <p>I tried using text2pcap too, for the conversion but that doesn't work in my case. Same for the mergecap. </p>