Rich Lane | 360bcca | 2013-08-23 17:10:14 -0700 | [diff] [blame^] | 1 | """ |
| 2 | Pcap file writer |
| 3 | """ |
| 4 | |
| 5 | import struct |
| 6 | |
| 7 | PcapHeader = struct.Struct("<LHHLLLL") |
| 8 | PcapPktHeader = struct.Struct("<LLLL") |
| 9 | |
| 10 | class PcapWriter(object): |
| 11 | def __init__(self, filename): |
| 12 | """ |
| 13 | Open a pcap file |
| 14 | """ |
| 15 | self.stream = file(filename, 'w') |
| 16 | |
| 17 | self.stream.write(PcapHeader.pack( |
| 18 | 0xa1b2c3d4, # magic |
| 19 | 2, # major |
| 20 | 4, # minor |
| 21 | 0, # timezone offset |
| 22 | 0, # timezone accuracy |
| 23 | 65535, # snapshot length |
| 24 | 1 # ethernet linktype |
| 25 | )) |
| 26 | |
| 27 | def write(self, data, timestamp): |
| 28 | """ |
| 29 | Write a packet to a pcap file |
| 30 | |
| 31 | 'data' should be a string containing the packet data. |
| 32 | 'timestamp' should be a float. |
| 33 | """ |
| 34 | self.stream.write(PcapPktHeader.pack( |
| 35 | int(timestamp), # timestamp seconds |
| 36 | int((timestamp - int(timestamp)) * 10**6), # timestamp microseconds |
| 37 | len(data), # truncated length |
| 38 | len(data) # un-truncated length |
| 39 | )) |
| 40 | self.stream.write(data) |
| 41 | |
| 42 | def close(self): |
| 43 | self.stream.close() |