private static void CompareFrame(XElement frame, Packet packet)
        {
            foreach (var field in frame.Fields())
            {
                switch (field.Name())
                {
//                    case "frame.time":
//                        string fieldShow = field.Show();
//                        if (fieldShow == "Not representable")
//                            break;
//                        fieldShow = fieldShow.Substring(0, fieldShow.Length - 2);
//                        DateTime fieldTimestamp = fieldShow[4] == ' '
//                                                      ? DateTime.ParseExact(fieldShow, "MMM  d, yyyy HH:mm:ss.fffffff", CultureInfo.InvariantCulture)
//                                                      : DateTime.ParseExact(fieldShow, "MMM dd, yyyy HH:mm:ss.fffffff", CultureInfo.InvariantCulture);
//                        MoreAssert.IsInRange(fieldTimestamp.AddSeconds(-2), fieldTimestamp.AddSeconds(2), packet.Timestamp, "Timestamp");
//                        break;

                case "frame.time_epoch":
                    double timeEpoch = double.Parse(field.Show(), CultureInfo.InvariantCulture);
                    // TODO: Remove this condition when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=11744 is fixed.
                    if (timeEpoch >= int.MinValue)
                    {
                        DateTime fieldTimestamp = new DateTime(1970, 1, 1).AddSeconds(timeEpoch);
                        MoreAssert.IsInRange(fieldTimestamp.AddMilliseconds(-1), fieldTimestamp.AddMilliseconds(1), packet.Timestamp.ToUniversalTime(),
                                             "Timestamp");
                    }
                    break;

                case "frame.cap_len":
                    field.AssertShowDecimal(packet.Length);
                    break;
                }
            }
        }
Esempio n. 2
0
        public void GetPacketTest()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";
            const int    NumPackets     = 10;

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

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

                PacketCommunicatorReceiveResult result;
                Packet actualPacket;
                for (int i = 0; i != NumPackets; ++i)
                {
                    result = communicator.ReceivePacket(out actualPacket);
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                    Assert.AreEqual(expectedPacket, actualPacket);
                    MoreAssert.IsInRange(expectedPacket.Timestamp.AddSeconds(-0.05), expectedPacket.Timestamp.AddSeconds(0.05),
                                         actualPacket.Timestamp);
                }

                result = communicator.ReceivePacket(out actualPacket);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Eof, result);
                Assert.IsNull(actualPacket);
            }
        }
Esempio n. 3
0
        public void SetSamplingMethodFirstAfterIntervalTest()
        {
            const int NumPackets = 10;

            Packet expectedPacket = _random.NextEthernetPacket(100);

            using (PacketCommunicator communicator = OpenOfflineDevice(NumPackets, expectedPacket, TimeSpan.FromSeconds(1)))
            {
                communicator.SetSamplingMethod(new SamplingMethodFirstAfterInterval(TimeSpan.FromSeconds(2)));

                PacketCommunicatorReceiveResult result;
                Packet packet;
                for (int i = 0; i != 5; ++i)
                {
                    result = communicator.ReceivePacket(out packet);
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                    Assert.AreEqual(expectedPacket, packet);
                    DateTime expectedTimestamp = expectedPacket.Timestamp.AddSeconds(i * 2);
                    MoreAssert.IsInRange(expectedTimestamp.AddSeconds(-0.01), expectedTimestamp.AddSeconds(0.01), packet.Timestamp);
                }
                result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Eof, result);
                Assert.IsNull(packet);
            }
        }
        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);
            }
        }
Esempio n. 5
0
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        private static void TestOpenMultipleTimes(int numTimes, string filename)
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";
            const int    NumPackets     = 10;
            Packet       expectedPacket = _random.NextEthernetPacket(100, SourceMac, DestinationMac);
            PacketDevice device         = GetOfflineDevice(NumPackets, expectedPacket, TimeSpan.Zero, Path.GetTempPath() + @"dump.pcap", Path.GetTempPath() + filename);

            for (int j = 0; j != numTimes; ++j)
            {
                using (PacketCommunicator communicator = device.Open())
                {
                    PacketCommunicatorReceiveResult result;
                    Packet actualPacket;
                    for (int i = 0; i != NumPackets; ++i)
                    {
                        result = communicator.ReceivePacket(out actualPacket);
                        Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                        Assert.AreEqual(expectedPacket, actualPacket);
                        MoreAssert.IsInRange(expectedPacket.Timestamp.AddSeconds(-0.05), expectedPacket.Timestamp.AddSeconds(0.05),
                                             actualPacket.Timestamp);
                    }

                    result = communicator.ReceivePacket(out actualPacket);
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Eof, result);
                    Assert.IsNull(actualPacket);
                }
            }
        }
Esempio n. 6
0
        public void OpenOfflineMultipleTimes()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";
            const int    NumPackets     = 10;
            Packet       expectedPacket = _random.NextEthernetPacket(100, SourceMac, DestinationMac);
            PacketDevice device         = GetOfflineDevice(NumPackets, expectedPacket);

            // TODO: Fix so we can go beyond 509.
            //       See http://www.winpcap.org/pipermail/winpcap-bugs/2012-December/001547.html
            for (int j = 0; j != 100; ++j)
            {
                using (PacketCommunicator communicator = device.Open())
                {
                    PacketCommunicatorReceiveResult result;
                    Packet actualPacket;
                    for (int i = 0; i != NumPackets; ++i)
                    {
                        result = communicator.ReceivePacket(out actualPacket);
                        Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                        Assert.AreEqual(expectedPacket, actualPacket);
                        MoreAssert.IsInRange(expectedPacket.Timestamp.AddSeconds(-0.05), expectedPacket.Timestamp.AddSeconds(0.05),
                                             actualPacket.Timestamp);
                    }

                    result = communicator.ReceivePacket(out actualPacket);
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Eof, result);
                    Assert.IsNull(actualPacket);
                }
            }
        }
        private static void CompareFrame(XElement frame, Packet packet)
        {
            foreach (var field in frame.Fields())
            {
                switch (field.Name())
                {
//                    case "frame.time":
//                        string fieldShow = field.Show();
//                        if (fieldShow == "Not representable")
//                            break;
//                        fieldShow = fieldShow.Substring(0, fieldShow.Length - 2);
//                        DateTime fieldTimestamp = fieldShow[4] == ' '
//                                                      ? DateTime.ParseExact(fieldShow, "MMM  d, yyyy HH:mm:ss.fffffff", CultureInfo.InvariantCulture)
//                                                      : DateTime.ParseExact(fieldShow, "MMM dd, yyyy HH:mm:ss.fffffff", CultureInfo.InvariantCulture);
//                        MoreAssert.IsInRange(fieldTimestamp.AddSeconds(-2), fieldTimestamp.AddSeconds(2), packet.Timestamp, "Timestamp");
//                        break;

                case "frame.time_epoch":
                    double   timeEpoch      = double.Parse(field.Show());
                    DateTime fieldTimestamp = new DateTime(1970, 1, 1).AddSeconds(timeEpoch);
                    MoreAssert.IsInRange(fieldTimestamp.AddMilliseconds(-1), fieldTimestamp.AddMilliseconds(1), packet.Timestamp.ToUniversalTime(), "Timestamp");
                    break;

                case "frame.cap_len":
                    field.AssertShowDecimal(packet.Length);
                    break;
                }
            }
        }
Esempio n. 8
0
        private static void TestReceivePacketsEnumerable(int numPacketsToSend, int numPacketsToWait, int numPacketsToBreakLoop, double secondsToWait,
                                                         int packetSize, 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);

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

                int    actualPacketsReceived = 0;
                Thread thread = new Thread(delegate()
                {
                    if (numPacketsToBreakLoop == 0)
                    {
                        communicator.Break();
                    }
                    IEnumerable <Packet> packets = numPacketsToWait == -1
                                                      ? communicator.ReceivePackets()
                                                      : communicator.ReceivePackets(numPacketsToWait);
                    foreach (Packet packet in packets)
                    {
                        Assert.AreEqual(sentPacket, packet);
                        ++actualPacketsReceived;
                        if (actualPacketsReceived == numPacketsToBreakLoop)
                        {
                            break;
                        }
                    }
                });

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

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

                Assert.AreEqual(expectedNumPackets, actualPacketsReceived, testDescription);
                MoreAssert.IsInRange(expectedMinSeconds, expectedMaxSeconds, (finishedWaiting - startWaiting).TotalSeconds, testDescription);
            }
        }
Esempio n. 9
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);
            }
        }
Esempio n. 10
0
 public void Handle(Packet packet)
 {
     Assert.AreEqual(_expectedPacket, packet);
     MoreAssert.IsInRange(_expectedMinTimestamp, _expectedMaxTimestamp, packet.Timestamp);
     ++_numPacketsHandled;
     if (NumPacketsHandled >= _numPacketsToBreakLoop)
     {
         _communicator.Break();
     }
 }
        private void ValidateExtensionHeaderUnnamedField(IpV6ExtensionHeader header, XElement headerField, ref int optionsIndex)
        {
            IpV6ExtensionHeaderOptions headerOptions = header as IpV6ExtensionHeaderOptions;

            string[] headerFieldShowParts = headerField.Show().Split(':');
            string   headerFieldShowName  = headerFieldShowParts[0];
            string   headerFieldShowValue = headerFieldShowParts[1];

            switch (headerFieldShowName)
            {
            case "Next header":
                headerField.AssertValue((byte)header.NextHeader.Value);
                break;

            case "Length":
                if (header.IsValid)
                {
                    Assert.IsTrue(headerFieldShowValue.EndsWith(" (" + header.Length + " bytes)"));
                }
                break;

            case "Router alert":
                IpV6OptionRouterAlert routerAlert = (IpV6OptionRouterAlert)headerOptions.Options[optionsIndex++];
                switch (headerFieldShowValue)
                {
                case " MLD (4 bytes)":
                    Assert.AreEqual(IpV6RouterAlertType.MulticastListenerDiscovery, routerAlert.RouterAlertType);
                    break;

                case " RSVP (4 bytes)":
                    Assert.AreEqual(IpV6RouterAlertType.Rsvp, routerAlert.RouterAlertType);
                    break;

                case " Unknown (4 bytes)":
                    MoreAssert.IsInRange((ushort)IpV6RouterAlertType.ActiveNetwork, (ushort)IpV6RouterAlertType.NextStepsInSignalingNatFirewallLayerProtocol, (ushort)routerAlert.RouterAlertType);
                    headerField.AssertValueInRange(0x05020002, 0x05020044);
                    break;

                default:
                    throw new InvalidOperationException("Invalid ipv6 header route Router alert value " + headerFieldShowValue);
                }
                break;

            case "Jumbo payload":
                IpV6OptionJumboPayload jumboPayload = (IpV6OptionJumboPayload)headerOptions.Options[optionsIndex++];
                Assert.AreEqual(" " + jumboPayload.JumboPayloadLength + " (6 bytes)", headerFieldShowValue);
                break;

            default:
                throw new InvalidOperationException("Invalid ipv6 header unnamed field show name " + headerFieldShowName);
            }
        }
Esempio n. 12
0
        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");
                }
            }
        }
Esempio n. 13
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);
            }
        }
        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);
            }
        }
Esempio n. 15
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);
            }
        }
Esempio n. 16
0
        public void ReceiveStatisticsTest()
        {
            const string SourceMac        = "11:22:33:44:55:66";
            const string DestinationMac   = "77:88:99:AA:BB:CC";
            const int    NumPacketsToSend = 100;
            const int    PacketSize       = 100;

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

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

                PacketSampleStatistics          statistics;
                PacketCommunicatorReceiveResult result = communicator.ReceiveStatistics(out statistics);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                MoreAssert.IsInRange(DateTime.Now.AddSeconds(-1), DateTime.Now.AddSeconds(1), statistics.Timestamp);
                Assert.AreEqual <ulong>(0, statistics.AcceptedPackets);
                Assert.AreEqual <ulong>(0, statistics.AcceptedBytes);

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

                result = communicator.ReceiveStatistics(out statistics);

                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                MoreAssert.IsInRange(DateTime.Now.AddSeconds(-1), DateTime.Now.AddSeconds(1), statistics.Timestamp);
                Assert.AreEqual <ulong>(NumPacketsToSend, statistics.AcceptedPackets, "AcceptedPackets");
                // Todo check byte statistics. See http://www.winpcap.org/pipermail/winpcap-users/2015-February/004931.html
//                Assert.AreEqual<long>((sentPacket.Length * NumPacketsToSend), statistics.AcceptedBytes,
//                                      "AcceptedBytes. Diff Per Packet: " +
//                                      (statistics.AcceptedBytes - sentPacket.Length * NumPacketsToSend) /
//                                      ((double)NumPacketsToSend));
            }
        }
Esempio n. 17
0
        public void RandomGreTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = new MacAddress("00:01:02:03:04:05"),
                Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
            };

            int seed = new Random().Next();

            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 200; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.Gre, false);

                GreLayer     greLayer     = random.NextGreLayer();
                PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100));

                PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, greLayer, payloadLayer);

                Packet packet = packetBuilder.Build(DateTime.Now);
                if (greLayer.Checksum == null &&
                    !new[] { EthernetType.IpV4, EthernetType.IpV6, EthernetType.Arp, EthernetType.VLanTaggedFrame }.Contains(packet.Ethernet.Ip.Gre.ProtocolType))
                {
                    Assert.IsTrue(packet.IsValid, "IsValid, ProtocolType=" + packet.Ethernet.Ip.Gre.ProtocolType);
                }

                // Ethernet
                ethernetLayer.EtherType = ipLayer == ipV4Layer ? EthernetType.IpV4 : EthernetType.IpV6;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
                ethernetLayer.EtherType = EthernetType.None;

                // IP.
                if (ipLayer == ipV4Layer)
                {
                    // IPv4.
                    ipV4Layer.Protocol       = IpV4Protocol.Gre;
                    ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.Ip.ExtractLayer()).HeaderChecksum;
                    Assert.AreEqual(ipV4Layer, packet.Ethernet.Ip.ExtractLayer());
                    ipV4Layer.HeaderChecksum = null;
                    Assert.AreEqual(ipV4Layer.Length, packet.Ethernet.IpV4.HeaderLength);
                    Assert.IsTrue(packet.Ethernet.IpV4.IsHeaderChecksumCorrect);
                    Assert.AreEqual(ipV4Layer.Length + greLayer.Length + payloadLayer.Length,
                                    packet.Ethernet.Ip.TotalLength);
                    Assert.AreEqual(IpV4Datagram.DefaultVersion, packet.Ethernet.Ip.Version);
                }
                else
                {
                    // IPv6.
                    Assert.AreEqual(ipLayer, packet.Ethernet.Ip.ExtractLayer());
                }

                // GRE
                GreDatagram actualGre      = packet.Ethernet.Ip.Gre;
                GreLayer    actualGreLayer = (GreLayer)actualGre.ExtractLayer();
                if (greLayer.ChecksumPresent && greLayer.Checksum == null)
                {
                    Assert.IsTrue(actualGre.IsChecksumCorrect);
                    greLayer.Checksum = actualGre.Checksum;
                }
                Assert.AreEqual(greLayer, actualGreLayer, "Layer");
                if (actualGreLayer.Key != null)
                {
                    actualGreLayer.SetKey(actualGreLayer.KeyPayloadLength.Value, actualGreLayer.KeyCallId.Value);
                }
                else
                {
                    Assert.IsNull(actualGreLayer.KeyPayloadLength);
                    Assert.IsNull(actualGreLayer.KeyCallId);
                }
                Assert.AreEqual(greLayer, actualGreLayer, "Layer");
                if (actualGre.KeyPresent)
                {
                    Assert.AreEqual(greLayer.KeyPayloadLength, actualGre.KeyPayloadLength, "KeyPayloadLength");
                    Assert.AreEqual(greLayer.KeyCallId, actualGre.KeyCallId, "KeyCallId");
                }
                Assert.AreNotEqual(random.NextGreLayer(), actualGreLayer, "Not Layer");
                Assert.AreEqual(greLayer.Length, actualGre.HeaderLength);
                Assert.IsTrue(actualGre.KeyPresent ^ (greLayer.Key == null));
                MoreAssert.IsSmaller(8, actualGre.RecursionControl);
                MoreAssert.IsSmaller(32, actualGre.FutureUseBits);
                Assert.IsTrue(actualGre.RoutingPresent ^ (greLayer.Routing == null && greLayer.RoutingOffset == null));
                Assert.IsTrue(actualGre.SequenceNumberPresent ^ (greLayer.SequenceNumber == null));
                Assert.IsTrue(!actualGre.StrictSourceRoute || actualGre.RoutingPresent);
                if (actualGre.RoutingPresent)
                {
                    Assert.IsNotNull(actualGre.ActiveSourceRouteEntryIndex);
                    if (actualGre.ActiveSourceRouteEntryIndex < actualGre.Routing.Count)
                    {
                        Assert.IsNotNull(actualGre.ActiveSourceRouteEntry);
                    }

                    foreach (GreSourceRouteEntry entry in actualGre.Routing)
                    {
                        Assert.AreNotEqual(entry, 2);
                        Assert.AreEqual(entry.GetHashCode(), entry.GetHashCode());
                        switch (entry.AddressFamily)
                        {
                        case GreSourceRouteEntryAddressFamily.AsSourceRoute:
                            GreSourceRouteEntryAs asEntry = (GreSourceRouteEntryAs)entry;
                            MoreAssert.IsInRange(0, asEntry.AsNumbers.Count, asEntry.NextAsNumberIndex);
                            if (asEntry.NextAsNumberIndex != asEntry.AsNumbers.Count)
                            {
                                Assert.AreEqual(asEntry.AsNumbers[asEntry.NextAsNumberIndex], asEntry.NextAsNumber);
                            }
                            break;

                        case GreSourceRouteEntryAddressFamily.IpSourceRoute:
                            GreSourceRouteEntryIp ipEntry = (GreSourceRouteEntryIp)entry;
                            MoreAssert.IsInRange(0, ipEntry.Addresses.Count, ipEntry.NextAddressIndex);
                            if (ipEntry.NextAddressIndex != ipEntry.Addresses.Count)
                            {
                                Assert.AreEqual(ipEntry.Addresses[ipEntry.NextAddressIndex], ipEntry.NextAddress);
                            }
                            break;

                        default:
                            GreSourceRouteEntryUnknown unknownEntry = (GreSourceRouteEntryUnknown)entry;
                            MoreAssert.IsInRange(0, unknownEntry.Data.Length, unknownEntry.PayloadOffset);
                            break;
                        }
                    }
                }
                else
                {
                    Assert.IsNull(actualGre.ActiveSourceRouteEntry);
                }

                Assert.IsNotNull(actualGre.Payload);
                switch (actualGre.ProtocolType)
                {
                case EthernetType.IpV4:
                    Assert.IsNotNull(actualGre.IpV4);
                    break;

                case EthernetType.Arp:
                    Assert.IsNotNull(actualGre.Arp);
                    break;
                }
            }
        }
        protected override bool CompareField(XElement field, Datagram datagram)
        {
            GreDatagram greDatagram = (GreDatagram)datagram;
            switch (field.Name())
            {
                case "gre.flags_and_version":
                    XElement[] innerFields = field.Fields().ToArray();
                    MoreAssert.IsInRange(8, 9, innerFields.Length);

                    int currentInnerFieldIndex = 0;
                    innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.ChecksumPresent);
                    innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.RoutingPresent);
                    innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.KeyPresent);
                    innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.SequenceNumberPresent);
                    innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.StrictSourceRoute);
                    innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.RecursionControl);
                    if (innerFields.Length == 9)
                    {
                        innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.AcknowledgmentSequenceNumberPresent);
                        innerFields[currentInnerFieldIndex++].AssertShowDecimal(greDatagram.FutureUseBits);
                    }
                    else
                    {
                        byte futureUseBitsValue = (byte)((greDatagram.AcknowledgmentSequenceNumberPresent.ToInt() << 4) | greDatagram.FutureUseBits);
                        innerFields[currentInnerFieldIndex++].AssertShowDecimal(futureUseBitsValue);
                    }
                    innerFields[currentInnerFieldIndex].AssertShowDecimal((byte)greDatagram.Version);
                    break;

                case "data.len":
                    field.AssertShowDecimal(
                        greDatagram.Payload.Length + (greDatagram.AcknowledgmentSequenceNumberPresent &&
                                                      (greDatagram.Version != GreVersion.EnhancedGre || !greDatagram.SequenceNumberPresent)
                                                          ? 4
                                                          : 0), "GRE data.len");
                    field.AssertNoFields();
                    break;

                case "gre.checksum":
                    field.AssertShowHex(greDatagram.Checksum);
                    field.AssertNoFields();
                    break;

                case "gre.key.payload_length":
                    field.AssertShowDecimal(greDatagram.KeyPayloadLength);
                    field.AssertNoFields();
                    break;

                case "gre.key.call_id":
                    field.AssertShowDecimal(greDatagram.KeyCallId);
                    field.AssertNoFields();
                    break;

                case "gre.ack_number":
                    field.AssertShowDecimal(greDatagram.AcknowledgmentSequenceNumber);
                    field.AssertNoFields();
                    break;

                case "gre.sequence_number":
                    field.AssertShowDecimal(greDatagram.SequenceNumber);
                    field.AssertNoFields();
                    break;

                case "gre.offset":
                    field.AssertShowDecimal(greDatagram.RoutingOffset);
                    field.AssertNoFields();
                    break;

                case "gre.routing":
                    field.AssertShow("");
                    field.AssertNoFields();
                    break;

                case "gre.routing.address_family":
                    if (_routingEntryIndex == greDatagram.Routing.Count)
                        field.AssertShowDecimal(0);
                    else
                        field.AssertShowDecimal((ushort)greDatagram.Routing[_routingEntryIndex].AddressFamily);
                    field.AssertNoFields();
                    break;

                case "gre.routing.sre_offset":
                    if (_routingEntryIndex == greDatagram.Routing.Count)
                        field.AssertShowDecimal(0);
                    else
                        field.AssertShowDecimal(greDatagram.Routing[_routingEntryIndex].PayloadOffset);
                    field.AssertNoFields();
                    break;

                case "gre.routing.src_length":
                    if (_routingEntryIndex == greDatagram.Routing.Count)
                        field.AssertShowDecimal(0);
                    else
                        field.AssertShowDecimal(greDatagram.Routing[_routingEntryIndex].PayloadLength);
                    field.AssertNoFields();
                    break;

                case "gre.routing.information":
                    if (_routingEntryIndex != greDatagram.Routing.Count)
                    {
                        switch (greDatagram.Routing[_routingEntryIndex].AddressFamily)
                        {
                            case GreSourceRouteEntryAddressFamily.IpSourceRoute:
                                field.AssertValue(((GreSourceRouteEntryIp)greDatagram.Routing[_routingEntryIndex]).Addresses);
                                break;

                            case GreSourceRouteEntryAddressFamily.AsSourceRoute:
                                field.AssertValue(((GreSourceRouteEntryAs)greDatagram.Routing[_routingEntryIndex]).AsNumbers);
                                break;

                            default:
                                field.AssertValue(((GreSourceRouteEntryUnknown)greDatagram.Routing[_routingEntryIndex]).Data);
                                break;
                        }

                        ++_routingEntryIndex;
                    }
                    field.AssertNoFields();
                    break;

                case "gre.proto":
                    field.AssertShowHex((ushort)greDatagram.ProtocolType);
                    field.AssertNoFields();
                    break;

                case "gre.key":
                    field.AssertShowHex(greDatagram.Key);
                    field.AssertNoFields();
                    break;

                case "data":
                case "data.data":
                    field.AssertDataField(greDatagram.Payload);
                    break;

                default:
                    Assert.Fail("Invalid field name: " + field.Name());
                    break;
            }

            return true;
        }
Esempio n. 19
0
 public static void AssertValueInRange(this XElement element, string expectedMinimumValue, string expectedMaximumValue)
 {
     MoreAssert.IsInRange(expectedMinimumValue, expectedMaximumValue, element.Value());
 }