public void Process_PacketBatch_TwoPacket() { var randomIPNonTcpPacket = IPPacket.RandomPacket(IPVersion.IPv4); var randomIPPacket = IPPacket.RandomPacket(IPVersion.IPv4); var randomTCPPacket = TcpPacket.RandomPacket(); randomIPPacket.PayloadPacket = randomTCPPacket; //Arrange var posixTimeval = new PosixTimeval(); var rawTCPCapture = new RawCapture(LinkLayers.Raw, posixTimeval, randomIPPacket.Bytes); var rawNonTCPCapture = new RawCapture(LinkLayers.Raw, posixTimeval, randomIPNonTcpPacket.Bytes); var rawPacketBatchRequest = new RawPacketBatchRequest( new[] { new RawPacket(rawTCPCapture), new RawPacket(rawNonTCPCapture), new RawPacket(rawTCPCapture) }, 1); //Act this._rawPacketBatchParserActorRefSUT.Tell(rawPacketBatchRequest); //Assert this._captureActorTestProbe.ExpectMsg <Frame>(frame => frame.TimestampTicks == posixTimeval.Date.Ticks); this._captureActorTestProbe.ExpectMsg <Frame>(frame => frame.TimestampTicks == posixTimeval.Date.Ticks); this._captureActorTestProbe.ExpectNoMsg(); }
/// <summary> /// IEnumerable helper allows for easy foreach usage, extension method and Linq usage /// </summary> /// <returns></returns> public static IEnumerable <RawCapture> GetSequence(ICaptureDevice dev, bool maskExceptions = true) { try { dev.Open(); while (true) { RawCapture packet = null; try { packet = dev.GetNextPacket(); } catch (PcapException pe) { if (!maskExceptions) { throw pe; } } if (packet == null) { break; } yield return(packet); } } finally { dev.Close(); } }
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (this.listBox1.SelectedIndex > 0) { RawCapture packet = this.packets[this.listBox1.SelectedIndex]; DynamicByteProvider provider = new DynamicByteProvider(packet.Data); this.hexBox1.ByteProvider = provider; this.textBox1.Text = Encoding.Default.GetString(packet.Data); this.treeView1.Nodes.Clear(); TreeNode header = this.treeView1.Nodes.Add("Header"); header.Nodes.Add(string.Format("Length: {0}", packet.Data.Length)); StringBuilder sb = new StringBuilder(); foreach (byte b in packet.Data) { sb.Append(b.ToString("00")); sb.Append(" "); } header.Nodes.Add(string.Format("Data: {0}", sb)); header.Nodes.Add(string.Format("Data length: {0}", packet.Data.Length.ToString())); header.Nodes.Add(string.Format("Date: {0}", packet.Timeval.Date.ToString())); header.Nodes.Add(string.Format("Microseconds: {0}", packet.Timeval.MicroSeconds.ToString())); header.Nodes.Add(string.Format("Seconds: {0}", packet.Timeval.Seconds.ToString())); this.treeView1.ExpandAll(); } }
private static IEnumerable <(RawCapture capture, IPv4Packet ipPacket, UdpPacket udpPacket)> Read(string file) { var device = new CaptureFileReaderDevice(file); device.Open(); RawCapture capture; while ((capture = device.GetNextPacket()) != null) { var packet = Packet.ParsePacket(capture.LinkLayerType, capture.Data); if (packet.PayloadPacket is not IPv4Packet ipPacket) { Console.WriteLine($"Skip packet {packet.PayloadPacket}"); continue; } if (ipPacket.Protocol != PacketDotNet.ProtocolType.Udp) { Console.WriteLine($"Skip packet of protocol {ipPacket.Protocol}"); continue; } var udpPacket = packet.Extract <UdpPacket>(); yield return(capture, ipPacket, udpPacket); } device.Close(); }
// tcp public void VerifyPacket0(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual(PhysicalAddress.Parse("00-13-10-03-71-47"), e.SourceHwAddress); Assert.AreEqual(PhysicalAddress.Parse("00-E0-4C-E5-73-AD"), e.DestinationHwAddress); IpPacket ip = (IpPacket)e.PayloadPacket; Assert.AreEqual(System.Net.IPAddress.Parse("82.165.240.134"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.221"), ip.DestinationAddress); Assert.AreEqual(IpVersion.IPv4, ip.Version); Assert.AreEqual(IPProtocolType.TCP, ip.Protocol); Assert.AreEqual(254, ip.TimeToLive); Assert.AreEqual(0x0df8, ((IPv4Packet)ip).CalculateIPChecksum()); Assert.AreEqual(1176685346, rawCapture.Timeval.Seconds); Assert.AreEqual(885259.000, rawCapture.Timeval.MicroSeconds); TcpPacket tcp = (TcpPacket)ip.PayloadPacket; Assert.AreEqual(80, tcp.SourcePort); Assert.AreEqual(4324, tcp.DestinationPort); Assert.IsTrue(tcp.Ack); Assert.AreEqual(3536, tcp.WindowSize); Assert.AreEqual(0xc835, tcp.CalculateTCPChecksum()); Console.WriteLine("tcp.Checksum is {0}", tcp.Checksum); Assert.AreEqual(0xc835, tcp.Checksum, "tcp.Checksum mismatch"); Assert.IsTrue(tcp.ValidTCPChecksum); }
private void Facto_Click1(object sender, EventArgs e) { int DeviceNum = Del_Button_Device(sender); CaptureDeviceList.Instance[DeviceNum].Open(DeviceMode.Normal, 0); RawCapture aRawCapture = CaptureDeviceList.Instance[DeviceNum].GetNextPacket(); //캡쳐 Print_TCP(aRawCapture.Data); //3계층 출력 }
public void WritePacket(RawCapture raw, PacketType type) { captureFileWriter.Write(raw); //if (type == PacketType.SIPDialog) //{ // var packet = PacketDotNet.Packet.ParsePacket(raw.LinkLayerType, raw.Data); // var udpPacket = PacketDotNet.UdpPacket.GetEncapsulated(packet); // SIPMessages.Add(udpPacket); //} if (type == PacketType.RTP) { var packet = PacketDotNet.Packet.ParsePacket(raw.LinkLayerType, raw.Data); var udpPacket = PacketDotNet.UdpPacket.GetEncapsulated(packet); // Only write out RTP packets to wav, and not RTPC if (udpPacket.SourcePort != this.CalleeRTCPPort || udpPacket.SourcePort != this.CallerRTCPPort) { if (wavOutput == null) { wavOutput = new WaveFileWriter("Calls\\" + CallID + ".wav", new WaveFormat(8000, 16, 1)); } for (int index = 0; index < udpPacket.PayloadData.Length; index++) { // assuming this is MuLaw, need to handle other formats like g729, g726 etc short pcm = MuLawDecoder.MuLawToLinearSample(udpPacket.PayloadData[index]); wavOutput.WriteByte((byte)(pcm & 0xFF)); wavOutput.WriteByte((byte)(pcm >> 8)); } } } }
public static void ParsePacket(RawCapture packet1) { var time = packet1.Timeval.Date; var len = packet1.Data.Length; var packet = PacketDotNet.Packet.ParsePacket(packet1.LinkLayerType, packet1.Data); var tcpPacket = PacketDotNet.TcpPacket.GetEncapsulated(packet); if (tcpPacket != null) { var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket; System.Net.IPAddress srcIp = ipPacket.SourceAddress; System.Net.IPAddress dstIp = ipPacket.DestinationAddress; int srcPort = tcpPacket.SourcePort; int dstPort = tcpPacket.DestinationPort; //OutPut(tcpPacket.AcknowledgmentNumber+" , "+tcpPacket.CalculateTCPChecksum()+" , "+tcpPacket.Checksum+" , "+tcpPacket.DataOffset+" , "+tcpPacket.SequenceNumber); string ipinfo = srcIp + ":" + srcPort + " ->" + dstIp + ":" + dstPort + " --Seq:" + tcpPacket.SequenceNumber + " DataLength:" + tcpPacket.PayloadData.Length + " NextSeq:" + (tcpPacket.SequenceNumber + tcpPacket.PayloadData.Length); if ((tcpPacket.PayloadData.Length == 0 && !IsFilterEmpty) || tcpPacket.PayloadData.Length > 0) { if (IsPrintIPInfo) { OutPut(ipinfo); } if (IsPrintDataInfo) { ParseData(tcpPacket); } } } }
public void setProtcolTree(RawCapture rawPacket, uint packetid) { if (frameNode == null) { frameNode = new TreeNode(); } frameNode.Nodes.Clear(); int len = rawPacket.Data.Length; string epochTime = rawPacket.Timeval.ToString(); string localTime = rawPacket.Timeval.Date.ToLocalTime().ToString(); frameNode.Text = string.Format("Frame {0}: {1} bytes on wire ({2} bits)", packetid, len, len * 8); frameNode.Nodes.Add(string.Format("Arrival Time: {0}", localTime)); frameNode.Nodes.Add(string.Format("Epoch Time: {0} seconds", epochTime)); frameNode.Nodes.Add(string.Format("Frame Number: {0}", packetid)); frameNode.Nodes.Add(string.Format("Frame Length: {0} bytes", len)); tree.Nodes.Add(frameNode); packet = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); switch (rawPacket.LinkLayerType) { case LinkLayers.Ethernet: Ethernet(packet); break; default: break; } }
// icmpv6 public void VerifyPacket0(Packet p, RawCapture rawCapture, LinkLayers linkLayer) { Assert.IsNotNull(p); Console.WriteLine(p.ToString()); Assert.AreEqual(linkLayer, rawCapture.LinkLayerType); if (linkLayer == LinkLayers.Ethernet) { EthernetPacket e = (EthernetPacket)p; Assert.AreEqual(PhysicalAddress.Parse("00-A0-CC-D9-41-75"), e.SourceHwAddress); Assert.AreEqual(PhysicalAddress.Parse("33-33-00-00-00-02"), e.DestinationHwAddress); } var ip = (IpPacket)p.Extract(typeof(IpPacket)); Console.WriteLine("ip {0}", ip.ToString()); Assert.AreEqual(System.Net.IPAddress.Parse("fe80::2a0:ccff:fed9:4175"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("ff02::2"), ip.DestinationAddress); Assert.AreEqual(IpVersion.IPv6, ip.Version); Assert.AreEqual(IPProtocolType.ICMPV6, ip.Protocol); Assert.AreEqual(16, ip.PayloadPacket.Bytes.Length, "ip.PayloadPacket.Bytes.Length mismatch"); Assert.AreEqual(255, ip.HopLimit); Assert.AreEqual(255, ip.TimeToLive); Assert.AreEqual(0x3a, (byte)ip.NextHeader); Console.WriteLine("Failed: ip.ComputeIPChecksum() not implemented."); Assert.AreEqual(1221145299, rawCapture.Timeval.Seconds); Assert.AreEqual(453568.000, rawCapture.Timeval.MicroSeconds); }
public unsafe void BenchmarkICaptureDeviceUnsafe() { int packetsRead = 0; var startTime = DateTime.Now; while (packetsRead < packetsToRead) { ICaptureDevice captureDevice = new SharpPcap.LibPcap.CaptureFileReaderDevice(TestHelper.GetFile("10k_packets.pcap")); captureDevice.Open(); RawCapture rawCapture = null; do { rawCapture = captureDevice.GetNextPacket(); packetsRead++; }while (rawCapture != null); captureDevice.Close(); } var endTime = DateTime.Now; var rate = new Rate(startTime, endTime, packetsRead, "packets captured"); Console.WriteLine("{0}", rate.ToString()); }
public async Task Run() { running = true; Console.WriteLine(); Console.WriteLine("-- Listening on {0}, hit 'ctrl-c' to stop...", _device.Name); while (running) { RawCapture capture = _device.GetNextPacket(); if (capture == null) { continue; } (string host, string endpoint, string agent, string accept) = _packetExtractor.Extract(capture); if (endpoint == null) { continue; } Parallel.Invoke(async() => await GetFile(host, endpoint, agent, accept)); } }
// udp public void VerifyPacket2(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual("0014BFF2EF0A", e.SourceHwAddress.ToString()); Assert.AreEqual("0016CFC91E29", e.DestinationHwAddress.ToString()); var ip = (IpPacket)p.Extract(typeof(IpPacket)); Assert.AreEqual(System.Net.IPAddress.Parse("172.210.164.56"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.104"), ip.DestinationAddress); Assert.AreEqual(IpVersion.IPv4, ip.Version); Assert.AreEqual(IPProtocolType.UDP, ip.Protocol); Assert.AreEqual(112, ip.TimeToLive); Assert.AreEqual(0xe0a2, ((IPv4Packet)ip).CalculateIPChecksum()); Assert.AreEqual(1171483602, rawCapture.Timeval.Seconds); Assert.AreEqual(578641.000, rawCapture.Timeval.MicroSeconds); var udp = (UdpPacket)p.Extract(typeof(UdpPacket)); Assert.AreEqual(52886, udp.SourcePort); Assert.AreEqual(56924, udp.DestinationPort); Assert.AreEqual(71, udp.Length); Assert.AreEqual(0xc8b8, udp.Checksum); }
public void BenchmarkICaptureDevice() { int packetsRead = 0; var startTime = DateTime.Now; while (packetsRead < packetsToRead) { ICaptureDevice captureDevice = new SharpPcap.LibPcap.CaptureFileReaderDevice(TestHelper.GetFile("10k_packets.pcap")); captureDevice.Open(); RawCapture rawCapture = null; do { rawCapture = captureDevice.GetNextPacket(); // Parse the packet using PacketDotNet if (rawCapture != null) { Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data); } packetsRead++; }while (rawCapture != null); captureDevice.Close(); } var endTime = DateTime.Now; var rate = new Rate(startTime, endTime, packetsRead, "packets parsed"); Console.WriteLine("{0}", rate.ToString()); }
private static void OnPacket(RawCapture capture) { if (capture.LinkLayerType != LinkLayers.Ethernet) { return; } var packet = Packet.ParsePacket(capture.LinkLayerType, capture.Data) as EthernetPacket; if (!IsSupportedPacket(packet)) { return; } var ipPacket = packet.PayloadPacket as IPPacket; bool success = false; if (ipPacket.Protocol == ProtocolType.Tcp || ipPacket.Protocol == ProtocolType.Udp) { success = Printer.Printer.PrintTcpAndUdpPackets(packet); } else if (ipPacket.Protocol == ProtocolType.Icmp || ipPacket.Protocol == ProtocolType.IcmpV6) { success = Printer.Printer.PrintICMPPackets(packet); } if (success && ++PacketCounter == Options.PacketCountLimit) { DisposeDevice(); Environment.Exit(AppCodes.Success); } }
/// <inheritdoc/> public bool GetNextFrame(out RawCapture frame, bool readData = true) { var ok = GetNextFrameInternal(); frame = _current; return(ok); }
/// <summary> /// Fires off on a seperate thread when a packet is available /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ProcessPacket(RawCapture incoming) { try { Packet packet = Packet.ParsePacket(LinkLayers.Ethernet, incoming.Data); EthernetPacket ethSrc = (EthernetPacket)packet.Extract(typeof(EthernetPacket)); IPv4Packet ipSrc = (IPv4Packet)packet.Extract(typeof(IPv4Packet)); if (ipSrc.Protocol == IPProtocolType.UDP) { UdpPacket udpSrc = (UdpPacket)packet.Extract(typeof(UdpPacket)); // From RFC 1002 Section 4.2.1.1 // Need to grab the transaction id for the reply UInt16 namedTrnId = BitConverter.ToUInt16(udpSrc.PayloadData, 0); // Looking for Response = query(0), OpCode = Query(0) // 11000000 00000000 UInt16 flags = Utility.ReverseUInt16(BitConverter.ToUInt16(udpSrc.PayloadData, 2)); if ((flags & 0xc000) == 0) { // Grab the name and make sure it's WPAD string name = Encoding.Default.GetString(udpSrc.PayloadData, 12, 34); if (Utility.DecodeName(name) == WpadHostName) { Logger.AddToInfoView("Received NBNS query for {0} from {1}", WpadHostName, ethSrc.SourceHwAddress); UdpPacket udpDst = new UdpPacket(NetbiosPort, NetbiosPort); udpDst.PayloadData = SetupResponse(namedTrnId, GetDeviceIp(this.Device)); IPv4Packet ipDst = new IPv4Packet(GetDeviceIp(this.Device), ipSrc.SourceAddress); ipDst.PayloadPacket = udpDst; udpDst.UpdateCalculatedValues(); udpDst.UpdateUDPChecksum(); ipDst.UpdateCalculatedValues(); ipDst.UpdateIPChecksum(); EthernetPacket ethDst = new EthernetPacket(this.Device.MacAddress, ethSrc.SourceHwAddress, EthernetPacketType.IpV4); ethDst.PayloadPacket = ipDst; ethDst.UpdateCalculatedValues(); Logger.AddToInfoView("Sending poisoned response for {0}", WpadHostName); this.Device.SendPacket(ethDst.Bytes); } } } else if (ipSrc.Protocol == IPProtocolType.TCP) { TcpPacket tcpSrc = (TcpPacket)packet.Extract(typeof(TcpPacket)); if (tcpSrc.Syn) { Logger.AddToInfoView("SYN sent {0}:{1}", ipSrc.DestinationAddress, tcpSrc.SourcePort); } } } catch (Exception ex) { Logger.AddToErrorView("OnPacketArrival", ex); } }
/// <summary> /// /// </summary> /// <param name="IPMy">本地Ip</param> /// <param name="IpYou">目标ip</param> private bool filterDataIp(string IPMy, string IpYou, RawCapture PacketD) { bool result = false; var packet = Packet.ParsePacket(PacketD.LinkLayerType, PacketD.Data); var tcpPacket = packet.Extract(typeof(TcpPacket)); if (tcpPacket != null) { var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket; IPAddress srcIp = ipPacket.SourceAddress; IPAddress dstIp = ipPacket.DestinationAddress; if ((srcIp.ToString() == IPMy || dstIp.ToString() == IPMy) && (srcIp.ToString() == IpYou || dstIp.ToString() == IpYou)) { result = true; } } else { var udpPacket = (UdpPacket)packet.Extract(typeof(UdpPacket)); if (udpPacket != null) { result = true; } } return(result); }
public static StatisticsRecord ConvertToStatistics(this RawCapture rawCapture) { var packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data); if (rawCapture.LinkLayerType == LinkLayers.Null) { packet = packet.PayloadPacket; } var statisticsRecord = new StatisticsRecord { Size = packet.TotalPacketLength, CapturedAt = rawCapture.Timeval.Date }; var discardStatistics = true; while (packet != null && ConfigurationManager.GetInstance().IsPacketTypeMonitored(packet.GetType())) { discardStatistics = false; ProtocolsLists.ProtocolParsersMapper[packet.GetType()].ParseProtocol(packet, statisticsRecord); packet = packet.PayloadPacket; } if (discardStatistics) { statisticsRecord = null; } return(statisticsRecord); }
// icmpv6 public void VerifyPacket0(Packet p, RawCapture rawCapture, LinkLayers linkLayers) { Assert.IsNotNull(p); Console.WriteLine(p.ToString()); Assert.AreEqual(linkLayers, rawCapture.GetLinkLayers()); if (linkLayers == LinkLayers.Ethernet) { var e = (EthernetPacket)p; Assert.AreEqual(PhysicalAddress.Parse("00-A0-CC-D9-41-75"), e.SourceHardwareAddress); Assert.AreEqual(PhysicalAddress.Parse("33-33-00-00-00-02"), e.DestinationHardwareAddress); } var ip = p.Extract <IPPacket>(); Console.WriteLine("ip {0}", ip); Assert.AreEqual(IPAddress.Parse("fe80::2a0:ccff:fed9:4175"), ip.SourceAddress); Assert.AreEqual(IPAddress.Parse("ff02::2"), ip.DestinationAddress); Assert.AreEqual(IPVersion.IPv6, ip.Version); Assert.AreEqual(ProtocolType.IcmpV6, ip.Protocol); Assert.AreEqual(16, ip.PayloadPacket.Bytes.Length, "ip.PayloadPacket.Bytes.Length mismatch"); Assert.AreEqual(255, ip.HopLimit); Assert.AreEqual(255, ip.TimeToLive); Console.WriteLine("Failed: ip.ComputeIPChecksum() not implemented."); Assert.AreEqual(1221145299, rawCapture.Timeval.Seconds); Assert.AreEqual(453568.000, rawCapture.Timeval.MicroSeconds); }
public void IgmpPacketCapture(object sender, CaptureEventArgs e) //Packet capture and return to string (async) { RawCapture capturePacket = e.Packet; try { if (this.NowCaptureNum <= this.CaptureNum) { var packet = PacketDotNet.Packet.ParsePacket(capturePacket.LinkLayerType, capturePacket.Data); IpPacket ipPacket = (IpPacket)packet.Extract(typeof(PacketDotNet.IpPacket)); if (ipPacket.Version != IpVersion.IPv4 || ipPacket.Protocol != IPProtocolType.IGMP) { return; } IGMPv2Packet igmpPacket = (IGMPv2Packet)ipPacket.Extract(typeof(PacketDotNet.IGMPv2Packet)); this.NowCaptureNum++; ResultData += "Header:" + igmpPacket.Header + "\n"; int i = 1; if (igmpPacket.PayloadData != null) { foreach (byte data in igmpPacket.PayloadData) { ResultData += Convert.ToString(data, 16) + " "; if (i % 8 == 0) { ResultData += "\n"; } i++; } } ResultData += "\n--------------------------------------------\n"; if (this.NowCaptureNum == this.CaptureNum) { StopPacketCapture(); } SendPacketData(); } else { StopPacketCapture(); //PacketCaptureDevice.Close(); CaptureEndEvent(); } } catch (NullReferenceException nullException) { Console.WriteLine(nullException.StackTrace); MessageBox.Show("Can't packet extracted. \n Are you set others protocol in filter?" , "Warining", System.Windows.MessageBoxButton.OK); StopPacketCapture(); //PacketCaptureDevice.Close(); } }
public void VerifyPacket1(Packet p, RawCapture rawCapture, LinkLayers linkLayers) { Assert.IsNotNull(p); Console.WriteLine(p.ToString()); Assert.AreEqual(linkLayers, rawCapture.GetLinkLayers()); if (linkLayers == LinkLayers.Ethernet) { var e = (EthernetPacket)p; Assert.AreEqual(PhysicalAddress.Parse("F894C22EFAD1"), e.SourceHardwareAddress); Assert.AreEqual(PhysicalAddress.Parse("333300000016"), e.DestinationHardwareAddress); } var ip = p.Extract <IPv6Packet>(); Console.WriteLine("ip {0}", ip); Assert.AreEqual(IPAddress.Parse("fe80::d802:3589:15cf:3128"), ip.SourceAddress); Assert.AreEqual(IPAddress.Parse("ff02::16"), ip.DestinationAddress); Assert.AreEqual(IPVersion.IPv6, ip.Version); Assert.AreEqual(ProtocolType.IcmpV6, ip.Protocol); Assert.AreEqual(28, ip.PayloadPacket.Bytes.Length, "ip.PayloadPacket.Bytes.Length mismatch"); Assert.AreEqual(1, ip.HopLimit); Assert.AreEqual(1, ip.TimeToLive); Assert.AreEqual(0x3a, (byte)ip.Protocol); Console.WriteLine("Failed: ip.ComputeIPChecksum() not implemented."); Assert.AreEqual(1543415539, rawCapture.Timeval.Seconds); Assert.AreEqual(841441.000, rawCapture.Timeval.MicroSeconds); Assert.AreEqual(1, ip.ExtensionHeaders.Count); Assert.AreEqual(6, ip.ExtensionHeaders[0].Payload.Length); }
public IProcessingResult OpenCapture(Uri uri) { using (this._pcapLoader) { this._pcapLoader.Open(uri); RawCapture rawCapture = null; do { rawCapture = this._pcapLoader.GetNextPacket(); // Parse the packet using PacketDotNet if (rawCapture == null) { continue; } var capture = rawCapture; var packet = Packet.ParsePacket(this._pcapLoader.LinkType, capture.Data); this.ProcessPacket(packet); } while (rawCapture != null); } return(null); }
// tcp public void VerifyPacket1(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual("0016CFC91E29", e.SourceHwAddress.ToString()); Assert.AreEqual("0014BFF2EF0A", e.DestinationHwAddress.ToString()); IpPacket ip = (IpPacket)p.PayloadPacket; Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.104"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("86.42.196.13"), ip.DestinationAddress); Assert.AreEqual(64, ip.TimeToLive); Assert.AreEqual(0x2ff4, ((IPv4Packet)ip).CalculateIPChecksum()); Assert.AreEqual(1171483600, rawCapture.Timeval.Seconds); Assert.AreEqual(125234.000, rawCapture.Timeval.MicroSeconds); TcpPacket tcp = (TcpPacket)ip.PayloadPacket; Assert.AreEqual(56925, tcp.SourcePort); Assert.AreEqual(50199, tcp.DestinationPort); Assert.IsTrue(tcp.Ack); Assert.IsTrue(tcp.Psh); Assert.AreEqual(16666, tcp.WindowSize); Assert.AreEqual(0x9b02, tcp.CalculateTCPChecksum()); Assert.AreEqual(0x9b02, tcp.Checksum); Assert.IsTrue(tcp.ValidTCPChecksum); }
public async Task <IProcessingResult> OpenCaptureAsync(Uri uri) { using (this._pcapLoader) { this._pcapLoader.Open(uri); RawCapture rawCapture = null; do { rawCapture = this._pcapLoader.GetNextPacket(); // Parse the packet using PacketDotNet if (rawCapture == null) { continue; } var capture = rawCapture; var packet = await Task.Run(() => Packet.ParsePacket(this._pcapLoader.LinkType, capture.Data)).ConfigureAwait(false); this.ProcessPacket(packet); } while (rawCapture != null); } await Task.CompletedTask.ConfigureAwait(false); return(null); }
public PacketWrapper(int id, RawCapture p) { this.id = id; Packet pac = Packet.ParsePacket(p.LinkLayerType, p.Data); tcpPacket = pac.Extract <TcpPacket>(); ipPacket = pac.Extract <IPPacket>(); }
public PacketWrapper(int id, RawCapture p) { this.id = id; Packet pac = Packet.ParsePacket(p.LinkLayerType, p.Data); tcpPacket = pac.Extract(typeof(TcpPacket)) as TcpPacket; ipPacket = pac.Extract(typeof(IpPacket)) as IpPacket; }
public PacketWrapper(TcpRecon tcpRecon) { Count = ++CaptureForm.packetCount; ipPacket = tcpRecon.IpPacket; rawCapture = tcpRecon.RawCapture; tcpPacket = tcpRecon.TcpPacket; Msg = tcpRecon.Msg.ToString(); }
/// <summary> /// Notify the OnPacketArrival delegates about a newly captured packet /// </summary> /// <param name="p"> /// A <see cref="RawCapture"/> /// </param> protected virtual void SendPacketArrivalEvent(RawCapture p) { if (OnPacketArrival != null) { //Invoke the packet arrival event OnPacketArrival(this, new CaptureEventArgs(p, this)); } }
// arp public void VerifyPacket4(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual("0018F84B17A0", e.SourceHwAddress.ToString()); Assert.AreEqual("FFFFFFFFFFFF", e.DestinationHwAddress.ToString()); }
internal StatisticsModePacket(RawCapture p) { this.Timeval = p.Timeval; this.m_pktData = p.Data; }
/// <summary> /// Marshal a chunk of captured packets into a packet list /// </summary> /// <param name="packetsBuffer"></param> /// <param name="bufferEnd"></param> /// <param name="packets"></param> protected virtual void MarshalPackets(IntPtr packetsBuffer, IntPtr bufferEnd, out List<RawCapture> packets) { RawCapture p; var linkType = LinkType; packets = new List<RawCapture>(); IntPtr bufferPointer = packetsBuffer; while (bufferPointer.ToInt64() < bufferEnd.ToInt64()) { // marshal the header var header = new AirPcapPacketHeader(bufferPointer); // advance the pointer to the packet data and marshal that data // into a managed buffer bufferPointer = new IntPtr(bufferPointer.ToInt64() + header.Hdrlen); var pkt_data = new byte[header.Caplen]; Marshal.Copy(bufferPointer, pkt_data, 0, (int)header.Caplen); p = new RawCapture(linkType, new PosixTimeval(header.TsSec, header.TsUsec), pkt_data); packets.Add(p); // advance the pointer by the size of the data // and round up to the next word offset since each frame header is on a word boundry int alignment = 4; var pointer = bufferPointer.ToInt64() + header.Caplen; pointer = AirPcapDevice.RoundUp(pointer, alignment); bufferPointer = new IntPtr(pointer); } }
/// <summary> /// Constructor for a statistics mode event /// </summary> /// <param name="packet"> /// A <see cref="RawCapture"/> /// </param> /// <param name="device"> /// A <see cref="PcapDevice"/> /// </param> public StatisticsModeEventArgs(RawCapture packet, PcapDevice device) : base(packet, device) { }
/// <summary> /// Constructor /// </summary> /// <param name="packet"> /// A <see cref="RawCapture"/> /// </param> /// <param name="device"> /// A <see cref="ICaptureDevice"/> /// </param> public CaptureEventArgs(RawCapture packet, ICaptureDevice device) { this.packet = packet; this.device = device; }
/// <summary> /// Add a packet to this send queue. /// </summary> /// <param name="packet">The packet to add</param> /// <returns>True if success, else false</returns> public bool Add( RawCapture packet ) { var data = packet.Data; var timeval = packet.Timeval; var header = new PcapHeader((uint)timeval.Seconds, (uint)timeval.MicroSeconds, (uint)data.Length, (uint)data.Length); return this.AddInternal(data, header); }
/// <summary> /// Notify the OnPacketArrival delegates about a newly captured packet /// </summary> /// <param name="p"> /// A <see cref="RawCapture"/> /// </param> override protected void SendPacketArrivalEvent(RawCapture p) { if(Mode == CaptureMode.Packets) { base.SendPacketArrivalEvent(p); } else if(Mode == CaptureMode.Statistics) { var handler = OnPcapStatistics; if(handler != null) { //Invoke the pcap statistics event handler(this, new StatisticsModeEventArgs(p, this)); } } }
/// <summary> /// Notify the OnPacketArrival delegates about a newly captured packet /// </summary> /// <param name="p"> /// A <see cref="RawCapture"/> /// </param> protected void SendPacketArrivalEvent(RawCapture p) { var handler = OnPacketArrival; if(handler != null ) { //Invoke the packet arrival event handler(this, new CaptureEventArgs(p, this)); } }
/// <summary> /// Gets the next packet captured on this device /// </summary> /// <param name="p"> /// A <see cref="RawCapture"/> /// </param> /// <returns> /// A <see cref="System.Int32"/> that contains the result code /// </returns> public virtual int GetNextPacket(out RawCapture p) { //Pointer to a packet info struct IntPtr header = IntPtr.Zero; //Pointer to a packet struct IntPtr data = IntPtr.Zero; int res = 0; // using an invalid PcapHandle can result in an unmanaged segfault // so check for that here ThrowIfNotOpen("Device must be opened via Open() prior to use"); // If a user is calling GetNextPacket() when the background capture loop // is also calling into libpcap then bad things can happen // // The bad behavior I (Chris M.) saw was that the background capture would keep running // but no more packets were captured. Took two days to debug and regular users // may hit the issue more often so check and report the issue here if(Started) { throw new InvalidOperationDuringBackgroundCaptureException("GetNextPacket() invalid during background capture"); } //Get a packet from winpcap res = LibPcapSafeNativeMethods.pcap_next_ex( PcapHandle, ref header, ref data); p = null; if(res>0) { //Marshal the packet if ( (header != IntPtr.Zero) && (data != IntPtr.Zero) ) { p = MarshalRawPacket(header, data); } } return res; }
/// <summary> /// Writes a packet to the pcap dump file associated with this device. /// </summary> /// <param name="p">The packet to write</param> public void Dump(RawCapture p) { var data = p.Data; var timeval = p.Timeval; var header = new PcapHeader(timeval.Seconds, timeval.MicroSeconds, (uint)data.Length, (uint)data.Length); Dump(data, header); }
/// <summary> /// Convert an unmanaged packet into a managed PacketDotNet.RawPacket /// </summary> /// <param name="header"> /// A <see cref="IntPtr"/> /// </param> /// <param name="data"> /// A <see cref="IntPtr"/> /// </param> /// <returns> /// A <see cref="RawCapture"/> /// </returns> protected virtual RawCapture MarshalRawPacket(IntPtr /* pcap_pkthdr* */ header, IntPtr data) { RawCapture p; // marshal the header var pcapHeader = new PcapHeader(header); var pkt_data = new byte[pcapHeader.CaptureLength]; Marshal.Copy(data, pkt_data, 0, (int)pcapHeader.CaptureLength); p = new RawCapture(LinkType, new PosixTimeval(pcapHeader.Seconds, pcapHeader.MicroSeconds), pkt_data); return p; }