コード例 #1
1
ファイル: ReceivePackets.cs プロジェクト: labeuze/source
 private void _Receive(int count = 0)
 {
     //using (_communicator = _device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
     //{
     //    _ppacketManager = new PPacketManager();
     //    if (_filter != null)
     //        _communicator.SetFilter(_filter);
     //    _communicator.ReceivePackets(0, ReceivePacketHandle);
     //}
     try
     {
         _communicator = _device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000);
         if (_dumpFile != null)
             _packetDumpFile = _communicator.OpenDump(_dumpFile);
         _ppacketManager = new PPacketManager();
         if (_filter != null)
             _communicator.SetFilter(_filter);
         _communicator.ReceivePackets(count, ReceivePacketHandle);
     }
     finally
     {
         if (_communicator != null)
         {
             _communicator.Dispose();
             _communicator = null;
         }
         if (_packetDumpFile != null)
         {
             _packetDumpFile.Dispose();
             _packetDumpFile = null;
         }
     }
 }
コード例 #2
0
        private static void Compare(XDocument document, IEnumerable <Packet> packets)
        {
            IEnumerator <Packet> packetEnumerator = packets.GetEnumerator();

            List <Packet> failedPackets  = new List <Packet>();
            StringBuilder failureMessage = new StringBuilder();

            // Parse XML
            int i = 1;

            foreach (var documentPacket in document.Element("pdml").Elements("packet"))
            {
                packetEnumerator.MoveNext();
                Packet packet = packetEnumerator.Current;

                try
                {
                    ComparePacket(packet, documentPacket);
                }
                catch (Exception e)
                {
                    failedPackets.Add(packet);
                    failureMessage.Append(new AssertFailedException("Failed comparing packet " + i + ". " + e.Message, e) + Environment.NewLine);
                }
                ++i;
            }

            if (failedPackets.Any())
            {
                PacketDumpFile.Dump(Path.GetTempPath() + "temp." + 1000 + ".pcap", failedPackets.First().DataLink.Kind, 65536, failedPackets);
                throw new AssertFailedException("Failed comparing " + failedPackets.Count + " packets:" + Environment.NewLine + failureMessage);
            }
        }
コード例 #3
0
        /// <summary>
        /// Setup filter and start capture
        /// Return when an error occurs or StopCapture is called
        /// </summary>
        /// <param name="callback">Callback to handle packets</param>
        /// <param name="ErrorMsg">When return contains the error description</param>
        public void StartCapture(HandlePacket callback, out string ErrorMsg)
        {
            // Check the link layer. We support only Ethernet
            if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
            {
                ErrorMsg = "This program works only on Ethernet networks.";
                return;
            }

            // Compile the filter
            using (BerkeleyPacketFilter filter =
                       communicator.CreateFilter(SnifferConfig.Filter.FilterString)) {
                communicator.SetFilter(filter);
            }

            using (PacketDumpFile dumpFile = communicator.OpenDump(DumpFileName))
            {
                try {
                    // start the capture
                    communicator.ReceivePackets(0,
                                                delegate(Packet packet)
                    {
                        dumpFile.Dump(packet);
                        callback(packet);
                    });
                }
                catch (Exception ex) {
                    ErrorMsg = ex.Message;
                }
            }

            ErrorMsg = null;
        }
コード例 #4
0
 public static void ResetDetailsDumper()
 {
     detailsDumper.Dispose();
     File.Delete(detailsFile);
     detailsFile   = Path.GetTempFileName();
     detailsDumper = communicator.OpenDump(detailsFile);
 }
コード例 #5
0
		public static void ResetDetailsDumper()
		{
			detailsDumper.Dispose();
			File.Delete(detailsFile);
			detailsFile = Path.GetTempFileName();
			detailsDumper = communicator.OpenDump(detailsFile);
		}
コード例 #6
0
        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);
            }
        }
コード例 #7
0
		public static void DumpDetailsPacket(Packet packet)
		{
			if (detailsDumper == null) {
				detailsFile = Path.GetTempFileName();
				detailsDumper = communicator.OpenDump(detailsFile);
			}
			detailsDumper.Dump(packet);
		}
コード例 #8
0
 public static void DumpDetailsPacket(Packet packet)
 {
     if (detailsDumper == null)
     {
         detailsFile   = Path.GetTempFileName();
         detailsDumper = communicator.OpenDump(detailsFile);
     }
     detailsDumper.Dump(packet);
 }
コード例 #9
0
        public void StartCapture()
        {
            var dev = LivePacketDevice.AllLocalMachine.FirstOrDefault(d => d.Name.Equals(Device.Name));

            if (dev == null)
            {
                return;
            }

            var token = Cancellation.Token;

            this.CaptureTask = new Task((state) =>
            {
                DumpOptions option = (DumpOptions)state;

                // Open device
                using (PacketCommunicator communicator = dev.Open(
                           65535, PacketDeviceOpenAttributes.Promiscuous,
                           250
                           ))
                {
                    if (option.Filter != null)
                    {
                        communicator.SetFilter(option.Filter);
                    }

                    using (PacketDumpFile dumpFile = communicator.OpenDump(option.Path))
                    {
                        int count           = 0;
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();

                        while (count < option.Count &&
                               stopwatch.ElapsedMilliseconds < option.Durance.TotalMilliseconds)
                        {
                            token.ThrowIfCancellationRequested();

                            Packet packet;
                            var result = communicator.ReceivePacket(out packet);

                            if (result == PacketCommunicatorReceiveResult.Ok)
                            {
                                dumpFile.Dump(packet);
                                count++;

                                if (option.Callback != null)
                                {
                                    option.Callback(null, new PacketArrivalEventArgs(packet));
                                }
                            }
                        }
                    }
                }
            }, Options, token, TaskCreationOptions.LongRunning);

            CaptureTask.Start();
        }
コード例 #10
0
ファイル: Test_Winpcap_dn_f.cs プロジェクト: 24/source_04
        public static void Test_DumpPacketsToFile_02()
        {
            // from project SavingPacketsToADumpFile
            _tr.WriteLine("Test_DumpPacketsToFile_02");

            string dumpFile = @"dump\dump.pcap";

            dumpFile = GetPath(dumpFile);
            _tr.WriteLine("dump to file \"{0}\"", dumpFile);

            PacketDevice device = SelectDevice();

            if (device == null)
            {
                return;
            }
            __communicator = null;
            //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution);
            _rs.OnAbortExecution = OnAbortExecution;
            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 (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    //if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                    //{
                    //    _tr.WriteLine("This program works only on Ethernet networks.");
                    //    return;
                    //}

                    // start the capture
                    //var query = from packet in communicator.ReceivePackets() select packet; // where !packet.IsValid

                    using (PacketDumpFile dump = __communicator.OpenDump(dumpFile))
                    {
                        _tr.WriteLine("Listening on " + device.Description + "...");

                        // start the capture
                        __communicator.ReceivePackets(0, dump.Dump);
                    }
                }
            }
            catch (Exception ex)
            {
                _tr.WriteLine(ex.Message);
            }
            finally
            {
                //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution);
            }
        }
コード例 #11
0
 private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
 {
     if (save.Checked)
     {
         using (PacketCommunicator communicator = selectedAdapter.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
         {
             using (PacketDumpFile dumpFile = communicator.OpenDump(fullpath + "Paquetes.pcap"))
             {
                 communicator.ReceivePackets(0, dumpFile.Dump);
             }
         }
     }
 }
コード例 #12
0
 private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
 {
     if (save.Checked)
     {
         using (PacketCommunicator communicator = selectedAdapter.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
         {
             using (PacketDumpFile dumpFile = communicator.OpenDump(@"E:\networks final\.pcap"))
             {
                 // start the capture
                 communicator.ReceivePackets(0, dumpFile.Dump);
             }
         }
     }
 }
コード例 #13
0
        public static OfflinePacketDevice GetOfflineDevice(int numPackets, Packet packet, TimeSpan intervalBetweenPackets, string dumpFilename, string readFilename = null)
        {
            if (readFilename == null)
            {
                readFilename = dumpFilename;
            }
            PacketCommunicator communicator;

            using (communicator = LivePacketDeviceTests.OpenLiveDevice())
            {
                using (PacketDumpFile dumpFile = communicator.OpenDump(dumpFilename))
                {
                    int lastPosition = 0;
                    for (int i = 0; i != numPackets; ++i)
                    {
                        if (intervalBetweenPackets != TimeSpan.Zero && i != 0)
                        {
                            DateTime timestamp = packet.Timestamp;
                            timestamp = timestamp.Add(intervalBetweenPackets);
                            packet    = new Packet(packet.Buffer, timestamp, packet.DataLink);
                        }
                        dumpFile.Dump(packet);
                        MoreAssert.IsBigger(lastPosition, dumpFile.Position);
                        lastPosition = dumpFile.Position;
                        dumpFile.Flush();
                    }
                }
            }

            if (readFilename != dumpFilename)
            {
                if (File.Exists(readFilename))
                {
                    File.Delete(readFilename);
                }
                File.Move(dumpFilename, readFilename);
            }

            OfflinePacketDevice device = new OfflinePacketDevice(readFilename);

            Assert.AreEqual(0, device.Addresses.Count);
            Assert.AreEqual(string.Empty, device.Description);
            Assert.AreEqual(DeviceAttributes.None, device.Attributes);
            Assert.AreEqual(readFilename, device.Name);

            return(device);
        }
コード例 #14
0
        private void SaveSniffing()
        {
            PacketDevice saveSelectedDevice = allDevices[ddlNetworkAdapters.SelectedIndex];

            using (PacketCommunicator PkCommunicator = saveSelectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                if (txtFilters.Text != "")
                {
                    PkCommunicator.SetFilter(txtFilters.Text);
                }

                using (PacketDumpFile PkDumpFile = PkCommunicator.OpenDump(pcap_file))
                {
                    PkCommunicator.ReceivePackets(0, PkDumpFile.Dump);
                }
            }
        }
コード例 #15
0
        /// <summary>
        /// Saves one packet to disk on default path
        /// </summary>
        /// <param name="packet"></param>
        public void TrySaveOnePacketToDisk(Packet packet, string fileName = "savedpacket")
        {
            if (packet is null)
            {
                throw new ArgumentNullException(nameof(packet));
            }

            string path = PathProvider.GetDefaultPathToSolution();

            fileName = ConstructFileNameUntilThereIsNoFileWithSameName(fileName, path, ".pcap");

            PacketDumpFile.Dump(path + fileName,
                                packet.DataLink.Kind,
                                packet.Length,
                                new List <Packet> {
                packet
            });
        }
コード例 #16
0
		public PacketSniffer(int DeviceIndex)
		{
			// Retrieve the device list from the local machine
			IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
			PacketDevice SelectedDevice = allDevices[DeviceIndex];

			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);

			if (detailsDumper == null) {
				detailsFile = Path.GetTempFileName();
				detailsDumper = communicator.OpenDump(detailsFile);
			}

			ResetDumpFile();
		}
コード例 #17
0
        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            //if (save.Checked)
            //{
            using (PacketCommunicator communicator = selectedAdapter.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                string folderName = @"D:\Temp";
                path = Path.Combine(folderName);
                System.IO.Directory.CreateDirectory(path);
                string fileName = System.IO.Path.GetRandomFileName();
                path = System.IO.Path.Combine(path, fileName);

                using (PacketDumpFile dumpFile = communicator.OpenDump(path))
                {
                    communicator.ReceivePackets(0, dumpFile.Dump);
                }
            }
            //}
        }
コード例 #18
0
        public PacketSniffer(int DeviceIndex)
        {
            // Retrieve the device list from the local machine
            IList <LivePacketDevice> allDevices     = LivePacketDevice.AllLocalMachine;
            PacketDevice             SelectedDevice = allDevices[DeviceIndex];

            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);

            if (detailsDumper == null)
            {
                detailsFile   = Path.GetTempFileName();
                detailsDumper = communicator.OpenDump(detailsFile);
            }

            ResetDumpFile();
        }
コード例 #19
0
 private void _Receive(int count = 0)
 {
     //using (_communicator = _device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
     //{
     //    _ppacketManager = new PPacketManager();
     //    if (_filter != null)
     //        _communicator.SetFilter(_filter);
     //    _communicator.ReceivePackets(0, ReceivePacketHandle);
     //}
     try
     {
         _communicator = _device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000);
         if (_dumpFile != null)
         {
             _packetDumpFile = _communicator.OpenDump(_dumpFile);
         }
         _ppacketManager = new PPacketManager();
         if (_filter != null)
         {
             _communicator.SetFilter(_filter);
         }
         _communicator.ReceivePackets(count, ReceivePacketHandle);
     }
     finally
     {
         if (_communicator != null)
         {
             _communicator.Dispose();
             _communicator = null;
         }
         if (_packetDumpFile != null)
         {
             _packetDumpFile.Dispose();
             _packetDumpFile = null;
         }
     }
 }
コード例 #20
0
ファイル: Program.cs プロジェクト: zwxu999/Pcap.Net
        static void Main(string[] args)
        {
            // Retrieve the device list from the local machine
            IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the list
            for (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                {
                    Console.WriteLine(" (" + device.Description + ")");
                }
                else
                {
                    Console.WriteLine(" (No description available)");
                }
            }

            int deviceIndex = 0;

            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // 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
            {
                // Check the link layer. We support only Ethernet for simplicity.
                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                {
                    Console.WriteLine("This program works only on Ethernet networks.");
                    return;
                }

                // Compile and set the filter
//                communicator.SetFilter("ip and tcp");

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

                // start the capture
                var query = from packet in communicator.ReceivePackets()
//                            where !packet.IsValid
                            select packet;

                using (PacketDumpFile dumpFile = communicator.OpenDump("dump.pcap"))
                {
                    foreach (Packet packet in query)
                    {
                        if (packet.Length <= 60 &&
                            packet.Ethernet.EtherType == EthernetType.IpV4 &&
                            packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp &&
                            packet.Ethernet.IpV4.Tcp.ControlBits == (TcpControlBits.Synchronize | TcpControlBits.Acknowledgment))
                        {
                            Console.WriteLine("Captured Packet " + packet.Timestamp);
                        }

//                        dumpFile.Dump(packet);
                    }
                }
            }
        }
コード例 #21
0
        public void WritePcapFile()
        {
            string filename = $"websock__{_srcIp}_{_srcPort}__{_dstIp}_{_dstPort}__" + _packets[0].Timestamp.ToString("hh-mm-ss-fff") + ".pcap";

            PacketDumpFile.Dump(filename, DataLinkKind.Ethernet, 65536, _packets);
        }
コード例 #22
0
ファイル: Test_Winpcap_dn_f.cs プロジェクト: 24/source_04
        public static void Test_DumpPacketsToFile_01()
        {
            // from project CaptureInvalidPackets
            _tr.WriteLine("Test_DumpPacketsToFile_01");

            string dumpFile = @"dump\dump.pcap";

            dumpFile = GetPath(dumpFile);
            _tr.WriteLine("dump to file \"{0}\"", dumpFile);

            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 + "...");

                    if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                    {
                        _tr.WriteLine("This program works only on Ethernet networks.");
                        return;
                    }

                    // start the capture
                    var query = from packet in communicator.ReceivePackets() select packet; // where !packet.IsValid

                    using (PacketDumpFile dump = communicator.OpenDump(dumpFile))
                    {
                        foreach (Packet packet in query)
                        {
                            if (packet.Length <= 60 &&
                                packet.Ethernet.EtherType == EthernetType.IpV4 &&
                                packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp &&
                                packet.Ethernet.IpV4.Tcp.ControlBits == (TcpControlBits.Synchronize | TcpControlBits.Acknowledgment))
                            {
                                _tr.WriteLine("Captured Packet " + packet.Timestamp);
                            }

                            _tr.WriteLine("dump packet " + packet.Timestamp);
                            dump.Dump(packet);
                            if (_rs.IsExecutionAborted())
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _tr.WriteLine(ex.Message);
            }
        }
コード例 #23
0
        private static void ComparePacketsToWireshark(IEnumerable <Packet> packets)
        {
            string pcapFilename = Path.GetTempPath() + "temp." + new Random().NextByte() + ".pcap";

#pragma warning disable 162
// ReSharper disable ConditionIsAlwaysTrueOrFalse
// ReSharper disable HeuristicUnreachableCode
            if (!IsRetry)
            {
                PacketDumpFile.Dump(pcapFilename, new PcapDataLink(packets.First().DataLink.Kind), PacketDevice.DefaultSnapshotLength, packets);
            }
            else
            {
                pcapFilename = Path.GetTempPath() + "temp." + RetryNumber + ".pcap";
                List <Packet> packetsList = new List <Packet>();
                using (PacketCommunicator communicator = new OfflinePacketDevice(pcapFilename).Open())
                {
                    communicator.ReceivePackets(-1, packetsList.Add);
                }
                packets = packetsList;
            }
// ReSharper restore HeuristicUnreachableCode
// ReSharper restore ConditionIsAlwaysTrueOrFalse
#pragma warning restore 162

            // Create pdml file
            string documentFilename = pcapFilename + ".pdml";
            using (Process process = new Process())
            {
                process.StartInfo = new ProcessStartInfo
                {
                    // Wireshark's preferences file is %APPDATA%\Wireshark\preferences
                    FileName  = WiresharkTsharkPath,
                    Arguments = "-o ip.check_checksum:TRUE " +
                                "-o ipv6.use_geoip:FALSE " +
                                "-o udp.check_checksum:TRUE " +
                                "-o tcp.relative_sequence_numbers:FALSE " +
                                "-o tcp.analyze_sequence_numbers:FALSE " +
                                "-o tcp.track_bytes_in_flight:FALSE " +
                                "-o tcp.desegment_tcp_streams:FALSE " +
                                "-o tcp.check_checksum:TRUE " +
                                "-o http.dechunk_body:FALSE " +
                                "-t r -n -r \"" + pcapFilename + "\" -T pdml",
                    WorkingDirectory       = WiresharkDiretory,
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    CreateNoWindow         = true
                };
                Console.WriteLine("Starting process " + process.StartInfo.FileName + " " + process.StartInfo.Arguments);
                Assert.IsTrue(process.Start());
                string output      = process.StandardOutput.ReadToEnd();
                string errorOutput = process.StandardError.ReadToEnd();
                process.WaitForExit();
                Console.WriteLine(errorOutput);
                File.WriteAllText(documentFilename, output);
                Assert.AreEqual(0, process.ExitCode);
            }

            // Fix pdml file
            string fixedDocumentFilename = documentFilename + ".fixed";
            File.WriteAllBytes(fixedDocumentFilename, new List <byte>(from b in File.ReadAllBytes(documentFilename)
                                                                      select b == 0x0A || b == 0x0D
                                                                                ? b
                                                                                : Math.Max((byte)0x20, Math.Min(b, (byte)0x7F))).ToArray());

            try
            {
                Compare(XDocument.Load(fixedDocumentFilename, LoadOptions.None), packets);
            }
            catch (Exception exception)
            {
                throw new AssertFailedException("Failed comparing packets in file " + pcapFilename + ". " + exception, exception);
            }
        }
コード例 #24
0
        static void Main(string[] args)
        {
            // Check command line
            if (args.Length != 1)
            {
                Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
                return;
            }

            // Retrieve the device list on the local machine
            IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the list
            for (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                {
                    Console.WriteLine(" (" + device.Description + ")");
                }
                else
                {
                    Console.WriteLine(" (No description available)");
                }
            }

            int deviceIndex = 0;

            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // 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
            {
                // Open the dump file
                using (PacketDumpFile dumpFile = communicator.OpenDump(args[0]))
                {
                    Console.WriteLine("Listening on " + selectedDevice.Description + "... Press Ctrl+C to stop...");

                    // start the capture
                    communicator.ReceivePackets(0, dumpFile.Dump);
                }
            }
        }
コード例 #25
0
 public void SendNullPacketsTest()
 {
     PacketDumpFile.Dump(@"dump.pcap", new PcapDataLink(DataLinkKind.Ethernet), PacketDevice.DefaultSnapshotLength, null);
     Assert.Fail();
 }