public void DumpWithoutDeviceTest()
        {
            string filename = Path.GetTempPath() + @"dump.pcap";

            Packet expectedPacket = PacketBuilder.Build(DateTime.Now,
                                                        new EthernetLayer
            {
                Source      = new MacAddress(1),
                Destination = new MacAddress(2),
                EtherType   = EthernetType.QInQ,
            },
                                                        new PayloadLayer
            {
                Data = new Datagram(new byte[] { 1, 2, 3 })
            });

            PacketDumpFile.Dump(filename, DataLinkKind.Ethernet, PacketDevice.DefaultSnapshotLength,
                                new[] { expectedPacket });

            using (PacketCommunicator communicator = new OfflinePacketDevice(filename).Open())
            {
                Packet actualPacket;
                PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out actualPacket);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                Assert.AreEqual(expectedPacket, actualPacket);
                MoreAssert.IsInRange(expectedPacket.Timestamp.AddMicroseconds(-2), expectedPacket.Timestamp.AddMicroseconds(1), actualPacket.Timestamp);
            }
        }
Exemple #2
0
        public void Receive(Action <Packet> callback)
        {
            // Open the device
            using (PacketCommunicator communicator =
                       _packetDevice.Open(65536,                                  // portion of the packet to capture
                                                                                  // 65536 guarantees that the whole packet will be captured on all the link layers
                                          PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                          1000))                                  // read timeout
            {
                Console.WriteLine("Listening on " + _packetDevice.Description + "...");

                // Retrieve the packets
                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        callback(packet);
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }
                } while (true);
            }
        }
Exemple #3
0
        public void StartCapturing()
        {
            using (PacketCommunicator communicator = CurrentDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        PacketBuffer.Enqueue(packet);
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }

                    if (PacketBuffer.Count == 1000)
                    {
                        if (queueIsFull != null)
                        {
                            queueIsFull();
                        }
                    }
                } while (true);
            }
        }
Exemple #4
0
        public void Handler()
        {
            var          devices        = GetDevices();
            PacketDevice selectedDevice = devices[4];


            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,
                                           PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                           1000))                                  // read timeout
            {
                communicator.SetFilter("tcp port 443");

                Console.WriteLine("Listening on " + selectedDevice.Description + "...");

                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" +
                                          packet.Length);
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }
                } while (true);
            }
        }
Exemple #5
0
        public void CaptureLivePackets()
        {
            using (Communicator = CreateLivePacketCommunicator())
            {
                Communicator.SetFilter(CaptureFilter);
                do
                {
                    PacketCommunicatorReceiveResult result = Communicator.ReceivePacket(out Packet incomingPacket);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        PacketInterpreter interpreter = PacketInterpreter.CreatePacketInterpreter(incomingPacket);
                        Console.WriteLine(interpreter.ToString());
                        break;

                    default:
                        Console.WriteLine("Error. Unable to determine reason.");
                        break;
                    }
                } while (true);
            };
        }
        public void ResolveDestinationMacFor(ScanningOptions options, CancellationToken ct)
        {
            using (PacketCommunicator communicator = options.Device.Open(65535, PacketDeviceOpenAttributes.None, 100))
            {
                Packet request = ArpPacketFactory.CreateRequestFor(options);
                communicator.SetFilter("arp and src " + options.TargetIP + " and dst " + options.SourceIP);
                communicator.SendPacket(request);

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        return;
                    }

                    Packet responce;
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out responce);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        communicator.SendPacket(request);
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        options.TargetMac = ParseSenderMacFrom(responce);
                        return;
                    }
                }
            }
        }
        public static void CapturePacket(IList <LivePacketDevice> allDevices)
        {
            PacketDevice selectedDevice = SelectDevice(allDevices);

            // Open the device
            using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                Console.WriteLine("Listening on " + selectedDevice.Description + "...");

                // Retrieve the packets
                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" +
                                          packet.Length);
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }
                } while (true);
            }
        }
Exemple #8
0
        /// <summary>
        /// Collect a group of packets.
        /// Similar to ReceivePackets() except instead of calling a callback the packets are returned as an IEnumerable.
        /// <seealso cref="PacketCommunicator.ReceivePackets"/>
        /// <seealso cref="PacketCommunicator.ReceiveSomePackets"/>
        /// </summary>
        /// <param name="communicator">The PacketCommunicator to work on</param>
        /// <param name="count">Number of packets to process. A negative count causes ReceivePackets() to loop until the IEnumerable break (or until an error occurs).</param>
        /// <returns>An IEnumerable of Packets to process.</returns>
        /// <exception cref="System.InvalidOperationException">Thrown if the mode is not Capture or an error occurred.</exception>
        /// <remarks>
        ///   <para>Only the first bytes of data from the packet might be in the received packet (which won't necessarily be the entire packet; to capture the entire packet, you will have to provide a value for snapshortLength in your call to PacketDevice.Open() that is sufficiently large to get all of the packet's data - a value of 65536 should be sufficient on most if not all networks).</para>
        ///   <para>If a break is called on the returned Enumerable before the number of packets asked for received, the packet that was handled while breaking the enumerable may not be the last packet read. More packets might be read. This is because this method actually loops over calls to ReceiveSomePackets()</para>
        /// </remarks>
        public static IEnumerable <Packet> ReceivePackets(this PacketCommunicator communicator, int count)
        {
            List <Packet> packets = new List <Packet>(Math.Min(Math.Max(0, count), 128));

            while (count != 0)
            {
                packets.Clear();

                int countGot;
                PacketCommunicatorReceiveResult result = communicator.ReceiveSomePackets(out countGot, count, packets.Add);
                if (count > 0)
                {
                    count -= countGot;
                }
                foreach (Packet packet in packets)
                {
                    yield return(packet);
                }

                if (result != PacketCommunicatorReceiveResult.Ok)
                {
                    break;
                }
            }
        }
Exemple #9
0
        private static void TestGetSomePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop,
                                               PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets,
                                               double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToGet=" + numPacketsToGet +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop;

            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            Packet expectedPacket = _random.NextEthernetPacket(100, SourceMac, DestinationMac);

            using (PacketCommunicator communicator = OpenOfflineDevice(numPacketsToSend, expectedPacket))
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                if (numPacketsToBreakLoop == 0)
                {
                    communicator.Break();
                }
                PacketHandler handler = new PacketHandler(expectedPacket, expectedMinSeconds, expectedMaxSeconds, communicator, numPacketsToBreakLoop);

                int numPacketsGot;
                PacketCommunicatorReceiveResult result = communicator.ReceiveSomePackets(out numPacketsGot, numPacketsToGet, handler.Handle);
                Assert.AreEqual(expectedResult, result);
                Assert.AreEqual(expectedNumPackets, numPacketsGot, "NumPacketsGot. Test: " + testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled, "NumPacketsHandled. Test: " + testDescription);
            }
        }
Exemple #10
0
        public void ReceiveSomePacketsGcCollectTest()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            const int NumPackets = 2;

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                Packet sentPacket = _random.NextEthernetPacket(100, SourceMac, DestinationMac);

                for (int i = 0; i != NumPackets; ++i)
                {
                    communicator.SendPacket(sentPacket);
                }

                int numGot;
                PacketCommunicatorReceiveResult result = communicator.ReceiveSomePackets(out numGot, NumPackets,
                                                                                         delegate
                {
                    GC.Collect();
                });
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                Assert.AreEqual(NumPackets, numGot);
            }
        }
Exemple #11
0
        public unsafe PacketCommunicatorReceiveResult ReceivePacket(out Packet packet)
        {
            this.AssertMode(PacketCommunicatorMode.Capture);
            pcap_pkthdr *pcapPkthdrPtr1;
            byte *       numPtr;
            PacketCommunicatorReceiveResult communicatorReceiveResult = this.RunPcapNextEx(&pcapPkthdrPtr1, &numPtr);

            if (communicatorReceiveResult != PacketCommunicatorReceiveResult.Ok)
            {
                packet = (Packet)null;
                return(communicatorReceiveResult);
            }
            IDataLink    dataLink           = (IDataLink) new PcapDataLink(\u003CModule\u003E.pcap_datalink(this._pcapDescriptor));
            byte *       unmanagedByteArray = numPtr;
            pcap_pkthdr *pcapPkthdrPtr2     = pcapPkthdrPtr1;
            DateTime     dateTime           = new DateTime();

            PacketTimestamp.PcapTimestampToDateTime((timeval *)pcapPkthdrPtr1, out dateTime);
            int offset = 0;
            int count  = *(int *)((IntPtr)pcapPkthdrPtr2 + 8L);

            byte[] data = MarshalingServices.UnamangedToManagedByteArray(unmanagedByteArray, offset, count);
            packet = new Packet(data, dateTime, dataLink);
            return(PacketCommunicatorReceiveResult.Ok);
        }
Exemple #12
0
        async void ReceiveResposnes()
        {
            await Task.Run(() =>
            {
                Packet pck;

                do
                {
                    if (!receiveTask)
                    {
                        return;
                    }


                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out pck);



                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        {
                            if (pck.DataLink.Kind != DataLinkKind.Ethernet)
                            {
                                continue;
                            }
                            EthernetDatagram ed = pck.Ethernet;

                            if (ed.EtherType != EthernetType.Arp)
                            {
                                continue;
                            }
                            ArpDatagram arppck = ed.Arp;

                            if (arppck.Operation != ArpOperation.Reply)
                            {
                                continue;
                            }


                            NetworkHost host = new NetworkHost {
                                IP = arppck.SenderProtocolIpV4Address.ToString(), MAC = ed.Source.ToString()
                            };
                            OnCaptureHost?.Invoke(host);



                            continue;
                        }

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }
                } while (true);
            });
        }
Exemple #13
0
        //Captures packets while issuing concurrent calls to update the GUI
        /// <summary>
        /// Capture packets and stores their information
        /// </summary>
        private void CapturePackets()
        {
            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[this.deviceIndex];
            int          prevInd        = 0;

            // Open the device
            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                                   // 65536 guarantees that the whole packet will be captured on all the link layers
                                           PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                           1000))                                  // read timeout
            {
                communicator.SetFilter(filter);
                while (captFlag)
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out Packet packet);
                    byte[] packetInfo;

                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        break;

                    case PacketCommunicatorReceiveResult.Ok:
                        IpV4Datagram ipv4 = packet.Ethernet.IpV4;
                        IpV4Protocol i    = ipv4.Protocol;

                        CougarPacket cp = new CougarPacket(packet.Timestamp.ToString("hh:mm:ss.fff"),
                                                           ++packetNumber,
                                                           packet.Length,
                                                           ipv4.Source.ToString(),
                                                           ipv4.Destination.ToString());

                        packetInfo = Encoding.ASCII.GetBytes(cp.ToString() + "\n");
                        packetBytes.Add(packetInfo);

                        this.Invoke((MethodInvoker)(() =>
                        {
                            packetView.Items.Add(new ListViewItem(cp.toPropertyArray()));

                            ++prevInd;
                            if (chkAutoScroll.Checked && prevInd > 12)
                            {
                                packetView.Items[packetView.Items.Count - 1].EnsureVisible();
                                prevInd = 0;
                            }
                        }));
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " should never be reached here");
                    }
                }
            }
        }
Exemple #14
0
        private void buttonAgKesfi_Click(object sender, EventArgs e) // Ağda bulunan ciahzların mac adresleri bu fonksiyon yardımıyla arp paketleri gönderilerek elde edilir.
        {
            byte altdeger = Convert.ToByte(textBox2.Text);           //Ağ keşfi için kullanılacak sınır ipler belirlendi.
            byte ustdeger = Convert.ToByte(textBox3.Text);           //Ağ keşfi için kullanılacak sınır ipler belirlendi.
            IList <LivePacketDevice> allDevices     = LivePacketDevice.AllLocalMachine;
            PacketDevice             selectedDevice = allDevices[2]; //Cihaz seçimi. Manuel olarak atanmıştır.

            using (PacketCommunicator communicator = selectedDevice.Open(100,
                                                                         PacketDeviceOpenAttributes.Promiscuous,
                                                                         1000))
            {
                //****************************** Ağ keşfi ******************************
                for (byte i = altdeger; i < ustdeger; i++) // Ağdaki istenilen ip aralığına arp paketleri gönderiir. Örn: "192.168.1.i"
                {
                    EthernetLayer ethernetLayer =
                        new EthernetLayer                                  //Ethernet Katmanı
                    {
                        Source      = new MacAddress(MacAdresim()),        //Kaynak mac adresi. Fonksiyondan çekildi.
                        Destination = new MacAddress("ff:ff:ff:ff:ff:ff"), //Hedef mac adresi. Broadcast yayın yapıldı.
                        EtherType   = EthernetType.None,
                    };

                    ArpLayer arpLayer =
                        new ArpLayer //Arp Katmanı
                    {
                        ProtocolType          = EthernetType.IpV4,
                        Operation             = ArpOperation.Request,
                        SenderHardwareAddress = new byte[] { 0x28, 0xd2, 0x44, 0x49, 0x7e, 0x2b }.AsReadOnly(),                                                                                          // Kaynak ac adresi.
                             SenderProtocolAddress = new byte[] { Convert.ToByte(IpParcala(0)), Convert.ToByte(IpParcala(1)), Convert.ToByte(IpParcala(2)), Convert.ToByte(IpParcala(3)) }.AsReadOnly(), // Kaynak Ip adresi IpParcala fonksiyonundan bloklar halinde çekildi.
                             TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),                                                                                                       // Hedef Mac Adresi. Öğrenilmek istenen parametre. Request paketlerinde 00:00:00:00:00:00
                             TargetProtocolAddress = new byte[] { Convert.ToByte(IpParcala(0)), Convert.ToByte(IpParcala(1)), Convert.ToByte(IpParcala(2)), i }.AsReadOnly(),                            // Hedef Ip adresi IpParcala fonksiyonundan bulunulan ağın ilk 3 bloğu alındı. Son blok i değeri ile döngüye sokuldu.
                    };

                    PacketBuilder builder   = new PacketBuilder(ethernetLayer, arpLayer);
                    Packet        arppacket = builder.Build(DateTime.Now); // Katmanlar paketlendi.
                    communicator.SendPacket(arppacket);                    // Arp paketi yayınlandı.


                    //****************************** ARP Paket dinleme ******************************
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("arp")) // Filtre uygulandı.
                    {
                        communicator.SetFilter(filter);
                    }
                    Packet packet;
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Ok:
                        if (!listBox1.Items.Contains(packet.Ethernet.Source + "\t\t\t@" + packet.Ethernet.Arp.SenderProtocolIpV4Address.ToString())) // Listbox'da oluşabilecek veri tekrarı önlendi.
                        {
                            listBox1.Items.Add(packet.Ethernet.Source + "\t\t\t@" + packet.Ethernet.Arp.SenderProtocolIpV4Address.ToString());       // Gelen Arp Paketlerinin Ethernet Katmanındna Source MAC Addres verisi çekildi.
                        }
                        break;
                    }
                }
            }
        }
Exemple #15
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            IPDict = new Dictionary <IpV4Address, int>();

            using (PacketCommunicator communicator = selectedDevice.Open(1024, PacketDeviceOpenAttributes.Promiscuous, 200))
            {
                Packet packet;

                using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp"))
                {
                    communicator.SetFilter(filter);
                }
                for (int i = 0; i < 10; i++)
                {
                    if (packetCaptureWorker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        IpV4Datagram ip = packet.Ethernet.IpV4;
                        if (ip.Source.ToString() == localIP.ToString())
                        {
                            if (IPDict.ContainsKey(ip.Destination))
                            {
                                IPDict[ip.Destination]++;
                            }
                            else
                            {
                                IPDict.Add(ip.Destination, 1);
                            }
                        }
                        else if (ip.Destination.ToString() == localIP.ToString())
                        {
                            if (IPDict.ContainsKey(ip.Source))
                            {
                                IPDict[ip.Source]++;
                            }
                            else
                            {
                                IPDict.Add(ip.Source, 1);
                            }
                        }
                        break;

                    default:
                        throw new InvalidOperationException();
                    }
                }
            }
        }
Exemple #16
0
        private static void TestGetStatistics(string sourceMac, string destinationMac, int numPacketsToSend, int numStatisticsToGather, int numStatisticsToBreakLoop, double secondsToWait, int packetSize,
                                              PacketCommunicatorReceiveResult expectedResult, int expectedNumStatistics, int expectedNumPackets, double expectedMinSeconds, double expectedMaxSeconds)
        {
            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.Mode = PacketCommunicatorMode.Statistics;

                communicator.SetFilter("ether src " + sourceMac + " and ether dst " + destinationMac);

                Packet sentPacket = _random.NextEthernetPacket(packetSize, sourceMac, destinationMac);

                PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None;
                int   numStatisticsGot = 0;
                ulong totalPackets     = 0;
                ulong totalBytes       = 0;
                for (int i = 0; i != numPacketsToSend; ++i)
                {
                    communicator.SendPacket(sentPacket);
                }

                if (numStatisticsToBreakLoop == 0)
                {
                    communicator.Break();
                }
                Thread thread = new Thread(delegate()
                {
                    result = communicator.ReceiveStatistics(numStatisticsToGather,
                                                            delegate(PacketSampleStatistics statistics)
                    {
                        Assert.IsNotNull(statistics.ToString());
                        totalPackets += statistics.AcceptedPackets;
                        totalBytes   += statistics.AcceptedBytes;
                        ++numStatisticsGot;
                        if (numStatisticsGot >= numStatisticsToBreakLoop)
                        {
                            communicator.Break();
                        }
                    });
                });

                DateTime startWaiting = DateTime.Now;
                thread.Start();

                if (!thread.Join(TimeSpan.FromSeconds(secondsToWait)))
                {
                    thread.Abort();
                }
                DateTime finishedWaiting = DateTime.Now;
                Assert.AreEqual(expectedResult, result, "Result");
                Assert.AreEqual(expectedNumStatistics, numStatisticsGot, "NumStatistics");
                Assert.AreEqual((ulong)expectedNumPackets, totalPackets, "NumPackets");
                // Todo check byte statistics. See http://www.winpcap.org/pipermail/winpcap-users/2015-February/004931.html
//                Assert.AreEqual((ulong)(numPacketsToSend * sentPacket.Length), totalBytes, "NumBytes");
                MoreAssert.IsInRange(expectedMinSeconds, expectedMaxSeconds, (finishedWaiting - startWaiting).TotalSeconds);
            }
        }
Exemple #17
0
        public void Start()
        {
            if (!string.IsNullOrEmpty(PhysicalAdapter))
            {
                _physical_insterface = GetNetworkInterfaceByAdapterName(PhysicalAdapter);
                if (_physical_insterface != null)
                {
                    _live_packet_device = _physical_insterface.GetLivePacketDevice();
                    if (_instance._live_packet_device != null)
                    {
                        _instance._packet_communicator = _instance._live_packet_device.Open(65536, PacketDeviceOpenAttributes.Promiscuous | PacketDeviceOpenAttributes.MaximumResponsiveness | PacketDeviceOpenAttributes.NoCaptureLocal, 50);
                        if (_instance._packet_communicator != null)
                        {
                            StringBuilder filter = new StringBuilder();
                            filter.Append(@"arp or ether dst FF:FF:FF:FF:FF:FF");
                            _adapter_hashtable = new Hashtable();
                            foreach (VirtualAdapter Adapter in _adapters)
                            {
                                _adapter_hashtable.Add(Adapter.HashCode, Adapter);
                                filter.AppendFormat(" or ether dst {0}", Adapter.MAC.ToString());
                            }
                            _packet_communicator.SetFilter(filter.ToString());

                            _instance._packet_process_thread = new Thread(new System.Threading.ParameterizedThreadStart(delegate(object obj)
                            {
                                PacketCommunicatorReceiveResult result = _instance._packet_communicator.ReceivePackets(-1, _instance.PacketProcess);
                                if (result != PacketCommunicatorReceiveResult.BreakLoop)
                                {
                                    throw new Exception(string.Format("Unexpected virutal network down: {0}", result.ToString()));
                                }
                            }));

                            _instance._packet_process_thread.Name     = "PacketProcessThread";
                            _instance._packet_process_thread.Priority = ThreadPriority.AboveNormal;
                            _instance._packet_process_thread.Start();
                        }
                        else
                        {
                            throw new Exception(String.Format("Failed to open live packet device: {0}", _instance._live_packet_device.Name));
                        }
                    }
                    else
                    {
                        throw new Exception(String.Format("Unable open network adapter: {0}", PhysicalAdapter));
                    }
                }
                else
                {
                    throw new Exception(string.Format("Invalid PhysicalAdapter setting: {0}\r\nThis device may not exist in current system!", PhysicalAdapter));
                }
            }
            else
            {
                throw new Exception("PhysicalAdapter cannot be empty!");
            }
        }
        private static void TestTransmitQueueToLive(int numPacketsToSend, int packetSize, double secondsBetweenTimestamps, bool isSynced)
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            List <Packet> packetsToSend;

            using (PacketSendBuffer queue = BuildQueue(out packetsToSend, numPacketsToSend, packetSize, SourceMac, DestinationMac, secondsBetweenTimestamps))
            {
                using (PacketCommunicator communicator = LivePacketDeviceTests.OpenLiveDevice())
                {
                    communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
                    communicator.Transmit(queue, isSynced);

                    DateTime lastTimestamp     = DateTime.MinValue;
                    int      numPacketsHandled = 0;
                    int      numPacketsGot;
                    PacketCommunicatorReceiveResult result =
                        communicator.ReceiveSomePackets(out numPacketsGot, numPacketsToSend,
                                                        delegate(Packet packet)
                    {
                        Assert.AreEqual(packetsToSend[numPacketsHandled], packet);
                        if (numPacketsHandled > 0)
                        {
                            TimeSpan expectedDiff;
                            if (isSynced)
                            {
                                expectedDiff =
                                    packetsToSend[numPacketsHandled].Timestamp -
                                    packetsToSend[numPacketsHandled - 1].Timestamp;
                            }
                            else
                            {
                                expectedDiff = TimeSpan.Zero;
                            }
                            TimeSpan actualDiff = packet.Timestamp - lastTimestamp;
                            MoreAssert.IsInRange(
                                expectedDiff.Subtract(TimeSpan.FromSeconds(0.06)),
                                expectedDiff.Add(TimeSpan.FromSeconds(0.1)),
                                actualDiff, "actualDiff");
                        }
                        lastTimestamp = packet.Timestamp;
                        ++numPacketsHandled;
                    });

                    Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                    Assert.AreEqual(numPacketsToSend, numPacketsGot, "numPacketsGot");
                    Assert.AreEqual(numPacketsToSend, numPacketsHandled, "numPacketsHandled");
                }
            }
        }
Exemple #19
0
        private void StartCapturing()
        {
            using (PacketCommunicator communicator = CurrentDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);

                    if (Filter != null)
                    {
                        communicator.SetFilter(Filter);
                    }

                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        PacketBuffer.Enqueue((new CustomPacket(packet)).ToString());
                        //PacketBuffer.Enqueue(SuspiciousPacketGenerator.GenerateSample(36, "0", rand, false));

                        int randomNumber = rand.Next(10);

                        if (randomNumber % 5 == 0)
                        {
                            PacketBuffer.Enqueue(SuspiciousPacketGenerator.GenerateSample(36, "0", rand, false));
                        }
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " should never be reached here");
                    }

                    lock (PacketBuffer)
                    {
                        if (PacketBuffer.Count >= PACKETS_COUNT_CONSTRAINT && !Pause)
                        {
                            string[] data = GetLastPackets();

                            if (queueIsFull != null)
                            {
                                queueIsFull(data);
                            }
                        }
                    }
                } while (true);
            }
        }
Exemple #20
0
        private static void TestReceivePackets(int numPacketsToSend, int numPacketsToWait, int numPacketsToBreakLoop, double secondsToWait, int packetSize,
                                               PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets,
                                               double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToWait=" + numPacketsToWait +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop + ". SecondsToWait=" +
                                     secondsToWait + ". PacketSize=" + packetSize;


            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                Packet sentPacket = _random.NextEthernetPacket(packetSize, SourceMac, DestinationMac);

                PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None;

                for (int i = 0; i != numPacketsToSend; ++i)
                {
                    communicator.SendPacket(sentPacket);
                }

                PacketHandler handler = new PacketHandler(sentPacket, communicator, numPacketsToBreakLoop);

                Thread thread = new Thread(delegate()
                {
                    if (numPacketsToBreakLoop == 0)
                    {
                        communicator.Break();
                    }
                    result = communicator.ReceivePackets(numPacketsToWait, handler.Handle);
                });

                DateTime startWaiting = DateTime.Now;
                thread.Start();

                if (!thread.Join(TimeSpan.FromSeconds(secondsToWait)))
                {
                    thread.Abort();
                }
                DateTime finishedWaiting = DateTime.Now;

                Assert.AreEqual(expectedResult, result, testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled);
                MoreAssert.IsInRange(expectedMinSeconds, expectedMaxSeconds, (finishedWaiting - startWaiting).TotalSeconds);
            }
        }
Exemple #21
0
        public static void Test_CapturingThePacketsWithoutTheCallback_01()
        {
            // from project CapturingThePacketsWithoutTheCallback
            _tr.WriteLine("Test_CapturingThePacketsWithoutTheCallback_01");
            PacketDevice device = SelectDevice();

            if (device == null)
            {
                return;
            }
            try
            {
                // Open the device : device.Open()
                //   snapshotLength = 65536, portion of the packet to capture 65536 guarantees that the whole packet will be captured on all the link layers
                //   attributes = PacketDeviceOpenAttributes.Promiscuous, promiscuous mode
                //   readTimeout = 1000
                using (PacketCommunicator communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    _tr.WriteLine("Listening on " + device.Description + "...");

                    // Retrieve the packets
                    Packet packet;
                    do
                    {
                        PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                        switch (result)
                        {
                        case PacketCommunicatorReceiveResult.Timeout:
                            // Timeout elapsed
                            continue;

                        case PacketCommunicatorReceiveResult.Ok:
                            _tr.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);
                            break;

                        default:
                            throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                        }
                        if (_rs.IsExecutionAborted())
                        {
                            break;
                        }
                    } while (true);
                }
            }
            catch (Exception ex)
            {
                _tr.WriteLine(ex.Message);
            }
        }
Exemple #22
0
        public unsafe PacketCommunicatorReceiveResult ReceiveStatistics(out PacketSampleStatistics statistics)
        {
            this.AssertMode(PacketCommunicatorMode.Statistics);
            pcap_pkthdr *packetHeader;
            byte *       packetData;
            PacketCommunicatorReceiveResult communicatorReceiveResult = this.RunPcapNextEx(&packetHeader, &packetData);

            if (communicatorReceiveResult != PacketCommunicatorReceiveResult.Ok)
            {
                throw new InvalidOperationException("Got result " + communicatorReceiveResult.ToString() + " in statistics mode");
            }
            statistics = new PacketSampleStatistics(packetHeader, packetData);
            return(PacketCommunicatorReceiveResult.Ok);
        }
Exemple #23
0
        // rewrite of the former method, implemented using ReceivePacket()
        // use this method in a timer, filter based on timer (active or not)
        private void FilterPortPacket(PacketCommunicator pm, string prot = "UDP")
        {
            Packet packet;
            PacketCommunicatorReceiveResult result = pm.ReceivePacket(out packet);

            switch (result)
            {
            case PacketCommunicatorReceiveResult.Ok:
                Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);
                break;

            default:
                throw new InvalidOperationException("The result " + result + " should never be reached here");
            }
        }
Exemple #24
0
        public void SetSamplingMethodFirstAfterIntervalTest()
        {
            Random random = new Random();

            MacAddress sourceMac      = random.NextMacAddress();
            MacAddress destinationMac = random.NextMacAddress();

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + sourceMac + " and ether dst " + destinationMac);
                communicator.SetSamplingMethod(new SamplingMethodFirstAfterInterval(TimeSpan.FromSeconds(1)));
                int numPacketsGot;
                communicator.ReceiveSomePackets(out numPacketsGot, 100, p => { });

                Packet[] packetsToSend = new Packet[11];
                packetsToSend[0] = _random.NextEthernetPacket(60, sourceMac, destinationMac);
                for (int i = 0; i != 10; ++i)
                {
                    packetsToSend[i + 1] = _random.NextEthernetPacket(60 * (i + 2), sourceMac, destinationMac);
                }

                List <Packet> packets = new List <Packet>(6);
                Thread        thread  = new Thread(() => packets.AddRange(communicator.ReceivePackets(6)));
                thread.Start();

                communicator.SendPacket(packetsToSend[0]);
                Thread.Sleep(TimeSpan.FromSeconds(0.7));
                for (int i = 0; i != 10; ++i)
                {
                    communicator.SendPacket(packetsToSend[i + 1]);
                    Thread.Sleep(TimeSpan.FromSeconds(0.55));
                }

                if (!thread.Join(TimeSpan.FromSeconds(10)))
                {
                    thread.Abort();
                }
                Assert.AreEqual(6, packets.Count, packets.Select(p => (p.Timestamp - packets[0].Timestamp).TotalSeconds + "(" + p.Length + ")").SequenceToString(", "));
                Packet packet;
                for (int i = 0; i != 6; ++i)
                {
                    Assert.AreEqual(60 * (i * 2 + 1), packets[i].Length, i.ToString());
                }
                PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result);
                Assert.IsNull(packet);
            }
        }
Exemple #25
0
        private void OpenDevice(PacketDevice selectedDevice)
        {
            // Open the device
            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,
                                           PacketDeviceOpenAttributes.MaximumResponsiveness,
                                           1000))
            {
                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                {
                    MessageHelper.PrintMessage("This program works only on Ethernet networks.");
                    return;
                }

                // Compile the filter
                using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp"))
                {
                    // Set the filter
                    communicator.SetFilter(filter);
                }

                MessageHelper.PrintMessage("Listening on " + selectedDevice.Description + "...");

                // start the capture
                MessageHelper.PrintMessage("Monitoring started. Press any key to stop and save the results into a text file", "warning");

                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        PacketHandler(packet);
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " should never be reached here");
                    }
                } while (!Console.KeyAvailable);

                repo.SaveMonitoringResultsToTextFile(FileLocation);
            }
        }
Exemple #26
0
        public void ReceiveStatisticsGcCollectTest()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            const int NumStatistics = 2;

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
                communicator.Mode = PacketCommunicatorMode.Statistics;

                PacketCommunicatorReceiveResult result = communicator.ReceiveStatistics(NumStatistics, delegate
                {
                    GC.Collect();
                });
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
            }
        }
        public void SendAndReceievePacketTest()
        {
            const string SourceMac        = "11:22:33:44:55:66";
            const string DestinationMac   = "77:88:99:AA:BB:CC";
            const int    NumPacketsToSend = 10;

            using (PacketCommunicator communicator = OpenLiveDevice(100))
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                Packet   packet;
                DateTime startWaiting = DateTime.Now;
                PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                DateTime finishedWaiting = DateTime.Now;

                Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result);
                Assert.AreEqual <uint>(0, communicator.TotalStatistics.PacketsCaptured);
                MoreAssert.IsInRange(TimeSpan.FromSeconds(0.99), TimeSpan.FromSeconds(1.075), finishedWaiting - startWaiting);

                Packet sentPacket = _random.NextEthernetPacket(200, 300, SourceMac, DestinationMac);

                DateTime startSendingTime = DateTime.Now;

                for (int i = 0; i != NumPacketsToSend; ++i)
                {
                    communicator.SendPacket(sentPacket);
                }

                DateTime endSendingTime = DateTime.Now;

                for (int i = 0; i != NumPacketsToSend; ++i)
                {
                    result = communicator.ReceivePacket(out packet);

                    Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                    Assert.AreEqual(100, packet.Length);
                    Assert.AreEqual <uint>(200, packet.OriginalLength);
                    MoreAssert.IsInRange(startSendingTime - TimeSpan.FromSeconds(1), endSendingTime + TimeSpan.FromSeconds(30), packet.Timestamp);
                }
                Assert.AreEqual <uint>(NumPacketsToSend, communicator.TotalStatistics.PacketsCaptured);
            }
        }
Exemple #28
0
        private static void TestReceiveSomePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop, int packetSize, bool nonBlocking,
                                                   PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets, double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToGet=" + numPacketsToGet +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop + ". PacketSize=" + packetSize +
                                     ". NonBlocking=" + nonBlocking;

            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            Packet packetToSend = _random.NextEthernetPacket(packetSize, SourceMac, DestinationMac);

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.NonBlocking = nonBlocking;
                Assert.AreEqual(nonBlocking, communicator.NonBlocking);
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                int numPacketsGot;
                for (int i = 0; i != numPacketsToSend; ++i)
                {
                    communicator.SendPacket(packetToSend);
                }

                if (numPacketsToBreakLoop == 0)
                {
                    communicator.Break();
                }

                PacketHandler handler                  = new PacketHandler(packetToSend, communicator, numPacketsToBreakLoop);
                DateTime      startWaiting             = DateTime.Now;
                PacketCommunicatorReceiveResult result = communicator.ReceiveSomePackets(out numPacketsGot, numPacketsToGet,
                                                                                         handler.Handle);
                DateTime finishedWaiting = DateTime.Now;

                Assert.AreEqual(expectedResult, result);
                Assert.AreEqual(expectedNumPackets, numPacketsGot, "NumPacketsGot. Test: " + testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled, "NumPacketsHandled. Test: " + testDescription);
                MoreAssert.IsInRange(expectedMinSeconds, expectedMaxSeconds, (finishedWaiting - startWaiting).TotalSeconds, testDescription);
            }
        }
        public async void StartCapturing()
        {
            //stopSignal = false;
            _communicator = _deviceService.DeviceWithDescription.Device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000);
            FireStatusChanged("Listening on " + _deviceService.DeviceWithDescription.Device.Description + "...");

            using (BerkeleyPacketFilter filter = _communicator.CreateFilter("tcp port 80 or 443"))
            {
                // Set the filter
                _communicator.SetFilter(filter);
            }

            Packet packet;
            PacketCommunicatorReceiveResult receiveResult;

            do
            {
                receiveResult = await Task.Factory.StartNew <PacketCommunicatorReceiveResult>(
                    () => {
                    PacketCommunicatorReceiveResult result = _communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        break;

                    case PacketCommunicatorReceiveResult.Ok:
                        PacketHandler(packet);
                        break;

                    case PacketCommunicatorReceiveResult.Eof:
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }
                    return(result);
                }
                    );
            } while (receiveResult != PacketCommunicatorReceiveResult.Eof);
        }
Exemple #30
0
        private static void TestReceivePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop,
                                               PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets,
                                               double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToGet=" + numPacketsToGet +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop;

            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            Packet expectedPacket = _random.NextEthernetPacket(24, SourceMac, DestinationMac);

            using (PacketCommunicator communicator = OpenOfflineDevice(numPacketsToSend, expectedPacket))
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                if (numPacketsToBreakLoop == 0)
                {
                    communicator.Break();
                }
                PacketHandler handler = new PacketHandler(expectedPacket, expectedMinSeconds, expectedMaxSeconds, communicator, numPacketsToBreakLoop);

                PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None;
                Thread thread = new Thread(delegate()
                {
                    result = communicator.ReceivePackets(numPacketsToGet, handler.Handle);
                });
                thread.Start();

                if (!thread.Join(TimeSpan.FromSeconds(5)))
                {
                    thread.Abort();
                }

                Assert.AreEqual(expectedResult, result, testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled);
            }
        }
        private static void TestGetSomePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop,
                                               PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets,
                                               double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToGet=" + numPacketsToGet +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop;

            const string SourceMac = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            Packet expectedPacket = _random.NextEthernetPacket(100, SourceMac, DestinationMac);

            using (PacketCommunicator communicator = OpenOfflineDevice(numPacketsToSend, expectedPacket))
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                if (numPacketsToBreakLoop == 0)
                    communicator.Break();
                PacketHandler handler = new PacketHandler(expectedPacket, expectedMinSeconds, expectedMaxSeconds, communicator, numPacketsToBreakLoop);

                int numPacketsGot;
                PacketCommunicatorReceiveResult result = communicator.ReceiveSomePackets(out numPacketsGot, numPacketsToGet, handler.Handle);
                Assert.AreEqual(expectedResult, result);
                Assert.AreEqual(expectedNumPackets, numPacketsGot, "NumPacketsGot. Test: " + testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled, "NumPacketsHandled. Test: " + testDescription);
            }
        }
        private static void TestReceivePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop,
                                               PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets,
                                               double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToGet=" + numPacketsToGet +
                         ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop;

            const string SourceMac = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            Packet expectedPacket = _random.NextEthernetPacket(24, SourceMac, DestinationMac);

            using (PacketCommunicator communicator = OpenOfflineDevice(numPacketsToSend, expectedPacket))
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                if (numPacketsToBreakLoop == 0)
                    communicator.Break();
                PacketHandler handler = new PacketHandler(expectedPacket, expectedMinSeconds, expectedMaxSeconds, communicator, numPacketsToBreakLoop);

                PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None;
                Thread thread = new Thread(delegate()
                {
                    result = communicator.ReceivePackets(numPacketsToGet, handler.Handle);
                });
                thread.Start();

                if (!thread.Join(TimeSpan.FromSeconds(5)))
                {
                    thread.Abort();
                }

                Assert.AreEqual(expectedResult, result, testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled);
            }
        }
        private static void TestGetStatistics(string sourceMac, string destinationMac, int numPacketsToSend, int numStatisticsToGather, int numStatisticsToBreakLoop, double secondsToWait, int packetSize,
                                              PacketCommunicatorReceiveResult expectedResult, int expectedNumStatistics, int expectedNumPackets, double expectedMinSeconds, double expectedMaxSeconds)
        {
            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.Mode = PacketCommunicatorMode.Statistics;

                communicator.SetFilter("ether src " + sourceMac + " and ether dst " + destinationMac);

                Packet sentPacket = _random.NextEthernetPacket(packetSize, sourceMac, destinationMac);

                PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None;
                int numStatisticsGot = 0;
                ulong totalPackets = 0;
                ulong totalBytes = 0;
                for (int i = 0; i != numPacketsToSend; ++i)
                    communicator.SendPacket(sentPacket);

                if (numStatisticsToBreakLoop == 0)
                    communicator.Break();
                Thread thread = new Thread(delegate()
                {
                    result = communicator.ReceiveStatistics(numStatisticsToGather,
                                                     delegate(PacketSampleStatistics statistics)
                                                     {
                                                         Assert.IsNotNull(statistics.ToString());
                                                         totalPackets += statistics.AcceptedPackets;
                                                         totalBytes += statistics.AcceptedBytes;
                                                         ++numStatisticsGot;
                                                         if (numStatisticsGot >= numStatisticsToBreakLoop)
                                                             communicator.Break();
                                                     });
                });

                DateTime startWaiting = DateTime.Now;
                thread.Start();

                if (!thread.Join(TimeSpan.FromSeconds(secondsToWait)))
                    thread.Abort();
                DateTime finishedWaiting = DateTime.Now;
                Assert.AreEqual(expectedResult, result, "Result");
                Assert.AreEqual(expectedNumStatistics, numStatisticsGot, "NumStatistics");
                Assert.AreEqual((ulong)expectedNumPackets, totalPackets, "NumPackets");
                // Todo check bytes statistics
                //                Assert.AreEqual<ulong>((ulong)(NumPacketsToSend * sentPacket.Length), totalBytes, "NumBytes");
                MoreAssert.IsInRange(expectedMinSeconds, expectedMaxSeconds, (finishedWaiting - startWaiting).TotalSeconds);
            }
        }
        private static void TestReceivePackets(int numPacketsToSend, int numPacketsToWait, int numPacketsToBreakLoop, double secondsToWait, int packetSize,
                                           PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets,
                                           double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToWait=" + numPacketsToWait +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop + ". SecondsToWait=" +
                                     secondsToWait + ". PacketSize=" + packetSize;


            const string SourceMac = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                Packet sentPacket = _random.NextEthernetPacket(packetSize, SourceMac, DestinationMac);

                PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None;

                for (int i = 0; i != numPacketsToSend; ++i)
                    communicator.SendPacket(sentPacket);

                PacketHandler handler = new PacketHandler(sentPacket, communicator, numPacketsToBreakLoop);

                Thread thread = new Thread(delegate()
                {
                    if (numPacketsToBreakLoop == 0)
                        communicator.Break();
                    result = communicator.ReceivePackets(numPacketsToWait, handler.Handle);
                });

                DateTime startWaiting = DateTime.Now;
                thread.Start();

                if (!thread.Join(TimeSpan.FromSeconds(secondsToWait)))
                    thread.Abort();
                DateTime finishedWaiting = DateTime.Now;

                Assert.AreEqual(expectedResult, result, testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled);
                MoreAssert.IsInRange(expectedMinSeconds, expectedMaxSeconds, (finishedWaiting - startWaiting).TotalSeconds);
            }
        }
        private static void TestReceiveSomePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop, int packetSize, bool nonBlocking,
                                                   PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets, double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToGet=" + numPacketsToGet +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop + ". PacketSize=" + packetSize +
                                     ". NonBlocking=" + nonBlocking;

            const string SourceMac = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            Packet packetToSend = _random.NextEthernetPacket(packetSize, SourceMac, DestinationMac);

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.NonBlocking = nonBlocking;
                Assert.AreEqual(nonBlocking, communicator.NonBlocking);
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                int numPacketsGot;
                for (int i = 0; i != numPacketsToSend; ++i)
                    communicator.SendPacket(packetToSend);

                if (numPacketsToBreakLoop == 0)
                    communicator.Break();

                PacketHandler handler = new PacketHandler(packetToSend, communicator, numPacketsToBreakLoop);
                DateTime startWaiting = DateTime.Now;
                PacketCommunicatorReceiveResult result = communicator.ReceiveSomePackets(out numPacketsGot, numPacketsToGet,
                                                                                         handler.Handle);
                DateTime finishedWaiting = DateTime.Now;

                Assert.AreEqual(expectedResult, result);
                Assert.AreEqual(expectedNumPackets, numPacketsGot, "NumPacketsGot. Test: " + testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled, "NumPacketsHandled. Test: " + testDescription);
                MoreAssert.IsInRange(expectedMinSeconds, expectedMaxSeconds, (finishedWaiting - startWaiting).TotalSeconds, testDescription);
            }
        }