blob: 6dce53036e67ccbf57771fc27f4c290fdb4e0217 [file] [log] [blame]
Rich Lane360bcca2013-08-23 17:10:14 -07001"""
2Pcap file writer
3"""
4
5import struct
6
7PcapHeader = struct.Struct("<LHHLLLL")
8PcapPktHeader = struct.Struct("<LLLL")
Rich Lanea9e64422013-08-26 13:56:24 -07009PPIPktHeader = struct.Struct("<BBHL")
10PPIAggregateField = struct.Struct("<HHL")
Rich Lane360bcca2013-08-23 17:10:14 -070011
12class PcapWriter(object):
13 def __init__(self, filename):
14 """
15 Open a pcap file
16 """
17 self.stream = file(filename, 'w')
18
19 self.stream.write(PcapHeader.pack(
20 0xa1b2c3d4, # magic
21 2, # major
22 4, # minor
23 0, # timezone offset
24 0, # timezone accuracy
25 65535, # snapshot length
Rich Lanea9e64422013-08-26 13:56:24 -070026 192 # PPI linktype
Rich Lane360bcca2013-08-23 17:10:14 -070027 ))
28
Rich Lanea9e64422013-08-26 13:56:24 -070029 def write(self, data, timestamp, port):
Rich Lane360bcca2013-08-23 17:10:14 -070030 """
31 Write a packet to a pcap file
32
33 'data' should be a string containing the packet data.
34 'timestamp' should be a float.
Rich Lanea9e64422013-08-26 13:56:24 -070035 'port' should be an integer port number.
Rich Lane360bcca2013-08-23 17:10:14 -070036 """
Rich Lanea9e64422013-08-26 13:56:24 -070037 ppi_len = PPIPktHeader.size + PPIAggregateField.size
Rich Lane360bcca2013-08-23 17:10:14 -070038 self.stream.write(PcapPktHeader.pack(
39 int(timestamp), # timestamp seconds
40 int((timestamp - int(timestamp)) * 10**6), # timestamp microseconds
Rich Lanea9e64422013-08-26 13:56:24 -070041 len(data) + ppi_len, # truncated length
42 len(data) + ppi_len # un-truncated length
Rich Lane360bcca2013-08-23 17:10:14 -070043 ))
Rich Lanea9e64422013-08-26 13:56:24 -070044 self.stream.write(PPIPktHeader.pack(
45 0, # version
46 0, # flags
47 ppi_len, # length
48 1, # ethernet dlt
49 ))
50 self.stream.write(PPIAggregateField.pack(8, PPIAggregateField.size - 4, port))
Rich Lane360bcca2013-08-23 17:10:14 -070051 self.stream.write(data)
52
53 def close(self):
54 self.stream.close()
Rich Lanea9e64422013-08-26 13:56:24 -070055
56if __name__ == "__main__":
57 import time
58 print("Writing test pcap to test.pcap")
59 pcap_writer = PcapWriter("test.pcap")
60 pcap_writer.write("\x00\x01\x02\x03\x04\x05\x00\x0a\x0b\x0c\x0d\x0e\x08\x00", time.time(), 42)
61 pcap_writer.close()