public void WritePacket(IPacket packet) { try { AbstractBlock abstractBlock = null; if (packet is AbstractBlock) { abstractBlock = packet as AbstractBlock; } else { abstractBlock = EnchantedPacketBlock.CreateEnchantedPacketFromIPacket(packet, OnException); } HeaderWithInterfacesDescriptions header = this.HeadersWithInterfaces.Last(); byte[] data = abstractBlock.ConvertToByte(header.Header.ReverseByteOrder, OnException); if (abstractBlock.AssociatedInterfaceID.HasValue) { if (abstractBlock.AssociatedInterfaceID.Value >= header.InterfaceDescriptions.Count) { throw new ArgumentOutOfRangeException(string.Format("[PcapNGWriter.WritePacket] Packet interface ID: {0} is greater than InterfaceDescriptions count: {1}", abstractBlock.AssociatedInterfaceID.Value, header.InterfaceDescriptions.Count)); } int maxLength = header.InterfaceDescriptions[abstractBlock.AssociatedInterfaceID.Value].SnapLength; if (data.Length > maxLength) { throw new ArgumentOutOfRangeException(string.Format("[PcapNGWriter.WritePacket] block length: {0} is greater than MaximumCaptureLength: {1}", data.Length, maxLength)); } } lock (syncRoot) { binaryWriter.Write(data); } } catch (Exception exc) { OnException(exc); } }
public void ReadPackets(System.Threading.CancellationToken cancellationToken) { AbstractBlock block; long prevPosition = 0; while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length && !cancellationToken.IsCancellationRequested) { try { lock (syncRoot) { prevPosition = binaryReader.BaseStream.Position; block = AbstractBlockFactory.ReadNextBlock(binaryReader, this.ReverseByteOrder, OnException); } if (block == null) { throw new Exception(string.Format("[ReadPackets] AbstractBlockFactory cannot read packet on position {0}", prevPosition)); } switch (block.BlockType) { case BaseBlock.Types.EnhancedPacket: { EnchantedPacketBlock enchantedBlock = block as EnchantedPacketBlock; if (enchantedBlock == null) { throw new Exception(string.Format("[ReadPackets] system cannot cast block to EnchantedPacketBlock. Block start on position: {0}.", prevPosition)); } else { OnReadPacket(enchantedBlock); } } break; case BaseBlock.Types.Packet: { PacketBlock packetBlock = block as PacketBlock; if (packetBlock == null) { throw new Exception(string.Format("[ReadPackets] system cannot cast block to PacketBlock. Block start on position: {0}.", prevPosition)); } else { OnReadPacket(packetBlock); } } break; case BaseBlock.Types.SimplePacket: { SimplePacketBlock simpleBlock = block as SimplePacketBlock; if (simpleBlock == null) { throw new Exception(string.Format("[ReadPackets] system cannot cast block to SimplePacketBlock. Block start on position: {0}.", prevPosition)); } else { OnReadPacket(simpleBlock); } } break; default: break; } } catch (Exception exc) { OnException(exc); lock (syncRoot) { if (prevPosition == binaryReader.BaseStream.Position) { break; } } continue; } } }