예제 #1
1
 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
1
            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the TAP interface
                PacketDevice selectedDevice = null;
                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.ToUpper().Contains(Guid.ToString().ToUpper()))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Load Balancer", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Load Balancer: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Load Balancer: Listening on " + Name + "...");
                        communicator.SetFilter("(ether dst " + ownHardwareAddressString + " and ((ip and (tcp or udp or icmp)) or arp)) or (ether dst FF:FF:FF:FF:FF:FF and arp)");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!ThreadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            if (packet.Ethernet.EtherType == EthernetType.Arp)
                            {
                                if (packet.Ethernet.Arp.TargetProtocolAddress.SequenceEqual(ownProtocolAddressByte) && packet.Ethernet.Arp.Operation == ArpOperation.Request)
                                {
                                    EthernetLayer ethernetLayer = new EthernetLayer
                                    {
                                        Source = ownHardwareAddress,
                                        Destination = packet.Ethernet.Source,
                                        EtherType = EthernetType.None,
                                    };

                                    ArpLayer arpLayer = new ArpLayer
                                    {
                                        ProtocolType = EthernetType.IpV4,
                                        Operation = ArpOperation.Reply,
                                        SenderHardwareAddress = ownHardwareAddressByte.AsReadOnly(),
                                        SenderProtocolAddress = packet.Ethernet.Arp.TargetProtocolAddress,
                                        TargetHardwareAddress = packet.Ethernet.Arp.SenderHardwareAddress,
                                        TargetProtocolAddress = packet.Ethernet.Arp.SenderProtocolAddress,
                                    };

                                    PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
                                    SendPacket(builder.Build(DateTime.Now));
                                }
                            }
                            else if (packet.Ethernet.EtherType.ToString() == "IpV4")
                            {

                                if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0)
                                {
                                    IpV4Handler(packet);
                                }
                                else if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset > 0)
                                {
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                        Global.ShowTrayTip("Load Balancer", "IP fragmentation detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    Global.WriteLog("Load Balancer: IP fragmentation detected on " + Name);
                                    //fragments = fragBuffer.Add(packet);
                                    //if (fragments != null)
                                    //    for (int i = 0; i < fragments.Count; i++)
                                    //    {
                                    //        IpV4Handler(fragments[i], fragments);
                                    //    }
                                }
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    if (ThreadActive.IsSet)
                    {
                        ThreadActive.Reset();
                        Global.WriteLog("Load Balancer: " + Name + " has disconnected");
                        if (Global.Config.Gadget.Debug)
                            Global.WriteLog(e.ToString());
                        Global.ShowTrayTip("Load Balancer", Name + " has disconnected", System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
예제 #3
1
            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the TAP interface
                PacketDevice selectedDevice = null;
                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.Contains(Guid))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Byte Counter", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Byte Counter: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Byte Counter: Listening on " + Name + "...");
                        communicator.SetFilter("((ether dst " + ifHardwareAddressString + " or ether src " + ifHardwareAddressString + ") and ip and (tcp or udp))");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!threadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            Table.CheckPacket(packet, ifHardwareAddress);
                        });
                    }
                }
                catch (Exception e)
                {
                    if (threadActive.IsSet)
                    {
                        threadActive.Reset();
                        Global.WriteLog("Byte Counter: Could not capture traffic from " + Name);
                        if (Global.Config.Gadget.Debug)
                            Global.WriteLog(e.ToString());
                        Global.ShowTrayTip("Byte Counter", "Could not capture traffic from " + Name, System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
예제 #4
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);
            }
        }
        public void StartHijack()
        {
            Task.Run(delegate {
                IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                if (allDevices.Count == 0)
                {
                    MessageBox.Show("未找到网卡。请确认已安装WinPcap。");
                    return;
                }

                foreach (var selectedDevice in allDevices)
                {
                    Task.Run(delegate
                    {
                        PacketCommunicator communicator =
                            selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000);
                        if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                        {
                            return;
                        }

                        using (BerkeleyPacketFilter filter = communicator.CreateFilter("tcp and dst port 80"))
                        {
                            communicator.SetFilter(filter);
                        }
                        communicator.ReceivePackets(0, PacketHandler);
                    });
                }

                this.BeginInvoke(new EventHandler(delegate {
                    lbMsg.Text = "监听已启动";
                }));
            });
        }
예제 #6
0
        private void PaketYakala(String filtre = "ip")
        {
            for (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
            }

            selectedDevice = allDevices[deviceIndex - 1];
            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 the filter
                using (BerkeleyPacketFilter filter = communicator.CreateFilter(filtre))
                {
                    // Set the filter
                    communicator.SetFilter(filter);
                }

                label2.Text = selectedDevice.Description;

                // start the capture
                communicator.ReceivePackets(0, PacketHandler);
            }
        }
예제 #7
0
        public void ReceivePacketsGcCollectTest()
        {
            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);
                }

                PacketCommunicatorReceiveResult result = communicator.ReceivePackets(NumPackets, delegate
                {
                    GC.Collect();
                });
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
            }
        }
예제 #8
0
파일: ArpMitm.cs 프로젝트: OMGtechy/Leho
        public void Execute(PacketCommunicator packetCommunicator)
        {
            SpoofGateway.Execute(packetCommunicator);
            SpoofTarget.Execute(packetCommunicator);

            packetCommunicator.ReceivePackets(-1, packet =>
            {
                if (packet.Ethernet.EtherType == EthernetType.Arp &&
                    packet.Ethernet.Arp.IsValid &&
                    packet.Ethernet.Arp.Operation == ArpOperation.Request)
                {
                    var senderMacAddress = packet.Ethernet.Arp.SenderHardwareAddress.ToArray().ReadMacAddress(0, Endianity.Big);

                    var sentByVictim   = senderMacAddress == VictimMacAddress;
                    var sentByGateway  = senderMacAddress == GatewayMacAddress;
                    var sentToAttacker = senderMacAddress == AttackerMacAddress;

                    var destinationIsVictim  = packet.Ethernet.Arp.TargetProtocolIpV4Address == VictimIpv4Address;
                    var destinationIsGateway = packet.Ethernet.Arp.TargetProtocolIpV4Address == GatewayIpv4Address;

                    var sentByTargetedDevice        = sentByVictim || sentByGateway;
                    var destinationIsTargetedDevice = destinationIsVictim || destinationIsGateway;

                    if (sentByTargetedDevice && destinationIsTargetedDevice)
                    {
                        new ArpReply(
                            AttackerMacAddress,
                            packet.Ethernet.Arp.TargetProtocolIpV4Address,
                            packet.Ethernet.Arp.SenderHardwareAddress.ToArray().ReadMacAddress(0, Endianity.Big),
                            packet.Ethernet.Arp.SenderProtocolIpV4Address
                            ).Execute(packetCommunicator);
                    }
                }
            });
        }
        public void Run()
        {
            if (selectedDevice != null)
            {
                using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Check the link layer. We support only Ethernet for simplicity.
                    if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                    {
                        CLI.PrintQueueLog(Channel.Zero, "이더넷 프로토콜에서만 작동합니다..", ConsoleColor.White);
                        return;
                    }
                    // Compile the filter
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and tcp and (port 80 or portrange 8000-9000)"))
                    {
                        // Set the filter
                        communicator.SetFilter(filter);
                    }

                    CLI.PrintQueueLog(Channel.Zero, "패킷 읽기 시작!", ConsoleColor.Yellow);
                    CLI.ShowToast("PCAP", "통발 블랙박스", "패킷 파싱을 시작합니다.", "");

                    // start the capture
                    communicator.ReceivePackets(0, PacketHandler);
                }
            }
            else
            {
                CLI.PrintQueueLog(Channel.Zero, "장치가 선택되지 않았습니다.", ConsoleColor.White);
            }
        }
예제 #10
0
        protected void StartCapture(LivePacketDevice dev)
        {
            if (dev == null)
            {
                return;
            }

            ExtraInfos[dev.Name].BackgroundThreadStop = false;
            ExtraInfos[dev.Name].BackgroundThread     = new Thread(BackgroundThread);
            ExtraInfos[dev.Name].BackgroundThread.Start(dev);
            ExtraInfos[dev.Name].BackgroundThread.IsBackground = true;
            ExtraInfos[dev.Name].CaptureCancellation           = new CancellationTokenSource();


            ThreadPool.QueueUserWorkItem(new WaitCallback(state =>
            {
                CancellationToken token = (CancellationToken)state;
                // Open device
                using (PacketCommunicator communicator = dev.Open(
                           65535, PacketDeviceOpenAttributes.Promiscuous,
                           250
                           ))
                {
                    while (!token.IsCancellationRequested)
                    {
                        communicator.ReceivePackets(200, packet =>
                        {
                            OnPacketArrivaled(packet, dev);
                        });
                    }
                }
            }), ExtraInfos[dev.Name].CaptureCancellation.Token);
        }
예제 #11
0
        public static void Test_ReadPacketsFromDumpFile_01()
        {
            // from project ReadingPacketsFromADumpFile
            _tr.WriteLine("Test_ReadPacketsFromDumpFile_01");

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

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

            // Create the offline device
            OfflinePacketDevice device = new OfflinePacketDevice(dumpFile);

            __communicator = null;
            //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution);
            _rs.OnAbortExecution = OnAbortExecution;
            try
            {
                // Open the capture file
                using (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Read and dispatch packets until EOF is reached
                    __communicator.ReceivePackets(0, ReadPacketsFromDumpFile);
                }
            }
            finally
            {
                //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution);
            }
        }
예제 #12
0
        /// <summary>
        /// Start an off-line capture
        /// </summary>
        /// <param name="file">The dump file name to capture</param>
        /// <param name="callback">Callback to handle packets</param>
        /// <param name="IsBadDumpFile">Flag indicates whether the dump file is invalid</param>
        public static void StartOfflineCapture(string file, HandlePacket callback, ref bool IsBadDumpFile)
        {
            PacketCommunicator pc = communicator;

            try {
                // Create the off-line device
                OfflinePacketDevice selectedDevice = new OfflinePacketDevice(file);

                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
                // Compile the filter
                using (BerkeleyPacketFilter filter =
                           communicator.CreateFilter(SnifferConfig.Filter.FilterString)) {
                    communicator.SetFilter(filter);
                }

                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, callback);
            }
            catch (Exception) {
                IsBadDumpFile = true;
            }
            finally {
                if (pc != null)
                {
                    communicator = pc;
                }
            }
        }
예제 #13
0
        static void Main(string[] args)
        {
            /* DESCOMENTAR ESTO PARA TESTEAR PREGUNTAS
             * Pregunta p = new Pregunta { Id = "1", Titulo= "De que son las nuevas materias creadas por la Universidad de Binghamtom?", Opcion1= "Huracanes", Opcion2= "Tornados", Opcion3= "Tempestades" };
             * // CargarPregunta(p, new List<int> { 0, 10, 0 });
             * //var lista = BuscarPregunta("Cual de estas novelas no tuvo segunda parte?", "El jardin del Eden", "Don quijote", "Ensayo sobre la ceguera");
             * // Retrieve the device list from the local machine
             * var resultado = BuscarPregunta("Cual de estos libros fue escrito por el argentino hernan vanoli?", "Una misma noche", "Pyongyang", "Ninguno de los dos");
             * CargarPregunta(p, resultado);*/
            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)");*/
            }
            string s = "--------------Esperando preguntas--------------";

            Console.WriteLine(s);
            int deviceIndex = 0;

            do
            {
                //Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = "1";
                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.None, // promiscuous mode
                                           1000))                           // read timeout
            {
                // Console.WriteLine("Listening on " + selectedDevice.Description + "...");

                // start the capture
                communicator.ReceivePackets(0, PacketHandler);
            }
        }
예제 #14
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;
        }
예제 #15
0
        // Long time operation
        public void Load(string filepath)
        {
            // file validation
            if (!Path.GetExtension(filepath).Equals(".pcap", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException("The file is nonexist or not valid");
            }

            Reset();

            dev = new OfflinePacketDevice(filepath);

            FileInfo info = new FileInfo(filepath);

            totalbytes = info.Length;

            ReportProgress(ProgressSource.Load, Prog_ReadFileStart, "读取文件...");


            // Read all packets from file until EOF
            using (PacketCommunicator communicator = dev.Open())
            {
                communicator.ReceivePackets(0, OnPacketArrival);
            }

            ReportProgress(ProgressSource.Load, Prog_SortPacketsStart, "对数据包排序...");
            plist.Sort();

            ReportProgress(ProgressSource.Load, Prog_AnalyzePacketsStart, "分析中...");
            Analyze();
            fileLoaded = true;

            ReportProgress(ProgressSource.Load, 100, "完成");
        }
예제 #16
0
        private void Run()
        {
            while (true)
            {
                iMutex.WaitOne();
                iStop = false;
                iMutex.ReleaseMutex();

                iStart.WaitOne();
                iStopped.Reset();
                iStarted.Set();

                iHalt = false;

                using (PacketCommunicator communicator = iRunningDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                {
                    Console.WriteLine("Listening on " + iRunningDevice.Description + "...");

                    try
                    {
                        communicator.ReceivePackets(0, PacketHandler);
                    }
                    catch (Exception)
                    {
                    }
                }

                iStarted.Reset();
                iStopped.Set();
            }
        }
예제 #17
0
        /// <summary>
        /// Captures packets via the selected device
        /// </summary>
        void ReadPackets(PacketDevice selectedDevice)
        {
            // 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)
                {
                    throw new FormatException("This program works only on Ethernet networks.");
                }

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

                // start the capture
                try
                {
                    communicator.ReceivePackets(0, PacketHandler);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Communicator: " + ex.Message);
                    return;
                }
            }
        }
예제 #18
0
        private void CapturePacket()
        {
            int deviceIndex = 0;

            try
            {
                deviceIndex = Int32.Parse(comboBoxInterfaces.SelectedValue.ToString());
            }
            catch
            {
            }


            // 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
            {
                labelDescription.Text = "Listening on " + InterFaces.Rows[deviceIndex - 1]["Description"] + "...";
                using (BerkeleyPacketFilter filter = communicator.CreateFilter("icmp"))
                {
                    // Set the filter
                    communicator.SetFilter(filter);
                }
                // start the capture
                communicator.ReceivePackets(0, DevicePingHandler);
            }
        }
예제 #19
0
        private void CreateListener()
        {
            IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Debug.WriteLine("No Network Interface Found! Please make sure WinPcap is properly installed.");
                return;
            }
            for (int i = 0; i != allDevices.Count; i++)
            {
                LivePacketDevice device = allDevices[i];
                if (device.Description != null)
                {
                    Debug.WriteLine(" (" + device.Description + ")");
                }
                else
                {
                    Debug.WriteLine(" (Unknown)");
                }
            }
            using (List <LivePacketDevice> .Enumerator enumerator = allDevices.ToList <LivePacketDevice>().GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    PacketDevice selectedDevice = enumerator.Current;
                    if (selectedDevice.Attributes == DeviceAttributes.Loopback)
                    {
                        continue;
                    }
                    new Thread(delegate()
                    {
                        try
                        {
                            using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                            {
                                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                                {
                                    Debug.WriteLine("This program works only on Ethernet networks.");
                                }
                                else
                                {
                                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp"))
                                    {
                                        communicator.SetFilter(filter);
                                    }
                                    Console.WriteLine("Capturing on " + selectedDevice.Description + "...");
                                    communicator.ReceivePackets(0, new HandlePacket(photonPacketHandler.PacketHandler));
                                }
                            }
                        }
                        catch (NotSupportedException ex)
                        {
                            Console.WriteLine($"Error listening on {selectedDevice.Description} because of {ex.Message}. Skipping this device. If it still works you can ignore this");
                        }
                    }).Start();
                }
            }
        }
예제 #20
0
 public void listen()
 {
     using (PacketCommunicator communicator = this.device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
     {
         communicator.SetFilter(this.filter);
         communicator.ReceivePackets(0, NAEHandler.PacketHandler);
     }
 }
예제 #21
0
 public static void sniffer(PacketDevice selectedDevice)
 {
     using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.DataTransferUdpRemote, 1000))
     {
         Console.WriteLine("Listening on {0} ...", selectedDevice.Description);
         communicator.ReceivePackets(0, PacketHandler);
     }
 }
예제 #22
0
            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the TAP interface
                PacketDevice selectedDevice = null;

                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.Contains(Guid))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Byte Counter", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Byte Counter: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Byte Counter: Listening on " + Name + "...");
                        communicator.SetFilter("((ether dst " + ifHardwareAddressString + " or ether src " + ifHardwareAddressString + ") and ip and (tcp or udp))");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!threadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            Table.CheckPacket(packet, ifHardwareAddress);
                        });
                    }
                }
                catch (Exception e)
                {
                    if (threadActive.IsSet)
                    {
                        threadActive.Reset();
                        Global.WriteLog("Byte Counter: Could not capture traffic from " + Name);
                        if (Global.Config.Gadget.Debug)
                        {
                            Global.WriteLog(e.ToString());
                        }
                        Global.ShowTrayTip("Byte Counter", "Could not capture traffic from " + Name, System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
예제 #23
0
        private void createListener()
        {
            IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                MessageBox.Show("No interfaces found! Make sure WinPcap is installed.");
                return;
            }
            // Print the list
            for (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];

                if (device.Description != null)
                {
                    Console.WriteLine(" (" + device.Description + ")");
                }
                else
                {
                    Console.WriteLine(" (No description available)");
                }
            }

            foreach (PacketDevice selectedDevice in allDevices.ToList())
            {
                // Open the device
                Thread t = new Thread(() =>
                {
                    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 the filter
                        using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp"))
                        {
                            // Set the filter
                            communicator.SetFilter(filter);
                        }

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

                        // start the capture
                        communicator.ReceivePackets(0, photonPacketHandler.PacketHandler);
                    }
                });
                t.Start();
            }
        }
예제 #24
0
        static void Main(string[] args)
        {
            // Lista urządzeń
            IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

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

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

            int deviceIndex = 0;

            //wprowadzanie numeru urzadzenia
            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);

            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Ustawiamy komunikator do przechwytywania z urządzenia
            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
            {
                // Filter
                Console.WriteLine("If you want, you can specify filter now");
                using (BerkeleyPacketFilter filter = communicator.CreateFilter(Console.ReadLine()))
                {
                    communicator.SetFilter(filter);
                }

                Console.WriteLine("Listening on " + selectedDevice.Description + "...");
                // przechwytywanie
                communicator.ReceivePackets(0, PacketHandler);
            }
        }
예제 #25
0
        private static void Sniff()
        {
            var device = LivePacketDevice.AllLocalMachine[5];

            using (PacketCommunicator pc = device.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 0))
            {
                pc.ReceivePackets(0, PacketHandler);
            }
        }
예제 #26
0
        private void HttpRecon(string saveDir, Collection <ExtractConstrain> coll)
        {
            if (!fileLoaded)
            {
                throw new InvalidOperationException("No file has been loaded");
            }

            ReportProgress(ProgressSource.HttpReconstruct, 0, "分析中...");
            using (TcpReassemble tcpre = new TcpReassemble())
            {
                // Reconstruct http files
                HttpReconstructor httpRecon = new HttpReconstructor();
                // Save result to files
                HttpConstrainExtract htf = new HttpConstrainExtract(saveDir);
                if (coll != null)
                {
                    foreach (var cons in coll)
                    {
                        htf.ConstrainCollection.Add(cons);
                    }
                }

                tcpre.ConnectionFinished += (o, e) =>
                {
                    httpRecon.OnConnectionFinished(e.Connection);
                    foreach (var rpy in httpRecon.ResponseList)
                    {
                        htf.OutputContent(rpy);
                    }
                };

                int cnt = 0;
                // Read all packets from file until EOF
                using (PacketCommunicator communicator = dev.Open())
                {
                    communicator.SetFilter("tcp");
                    communicator.ReceivePackets(0, p =>
                    {
                        tcpre.AddPacket(p.Ethernet.IpV4);
                        ReportProgress(ProgressSource.HttpReconstruct,
                                       (int)((double)cnt / plist.Count),
                                       string.Format("分析中...{0}/{1}", ++cnt, plist.Count));
                    });
                }

                ReportProgress(ProgressSource.HttpReconstruct, 100, "完成...打开文件夹...");
            }

            // Open folder
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
            {
                UseShellExecute = true,
                FileName        = saveDir,
                Verb            = "open"
            });
        }
예제 #27
0
        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
            {
                Console.WriteLine("Listening on " + selectedDevice.Description + "...");
                SelectedDeviceMac = PcapDotNet.Core.Extensions.LivePacketDeviceExtensions.GetMacAddress(allDevices[deviceIndex - 1]);
                // start the capture
                communicator.ReceivePackets(0, PacketHandler);
            }
        }
예제 #28
0
        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);
            }
        }
예제 #29
0
        private void FilterPortPackets(PacketCommunicator pm, string prot = "UDP")
        {
            string f = prot.ToLower() + " port " + Ports[0].Number;

            Console.WriteLine(f);
            using (BerkeleyPacketFilter filter = pm.CreateFilter(f))
            {
                pm.SetFilter(filter);
            }
            pm.ReceivePackets(5, PrintPacketInfo);
        }
        public static void CapturingPackets(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 + "...");
                communicator.ReceivePackets(0, new HandlePacket(albionPacketHandler.Packethandler));
            }
        }
예제 #31
0
        private void Start()
        {
            var device = PacketDeviceSelector.AskForPacketDevice();

            // var device = new OfflinePacketDevice("dump.pcap"); // Your wireshark dump (IT MUST BE *.pcap)

            using (PacketCommunicator communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                communicator.ReceivePackets(0, PacketHandler);
            }
        }
예제 #32
0
파일: MainForm.cs 프로젝트: yueding/HSBuddy
        private void readtcpdata()
        {
            IList <LivePacketDevice> allDevices     = LivePacketDevice.AllLocalMachine;
            PacketDevice             selectedDevice = allDevices[1]; //3

            using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                communicator.SetFilter("port 1119 or port 3724");
                communicator.ReceivePackets(0, DispatcherHandler);
            }
        }
예제 #33
0
 static void StartSniffing()
 {
     using (PacketCommunicator communicator = _selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
     {
         Console.WriteLine("Listening on " + _selectedDevice.Description + "...", Color.Coral);
         //using (BerkeleyPacketFilter filter = communicator.CreateFilter("udp"))
         //{
         //    communicator.SetFilter(filter);
         //}
         communicator.ReceivePackets(0, PacketHandler);
     }
 }
예제 #34
0
		/// <summary>
		/// Start an off-line capture
		/// </summary>
		/// <param name="file">The dump file name to capture</param>
		/// <param name="callback">Callback to handle packets</param>
		/// <param name="IsBadDumpFile">Flag indicates whether the dump file is invalid</param>
		public static void StartOfflineCapture(string file, HandlePacket callback, ref bool IsBadDumpFile)
		{
			PacketCommunicator pc = communicator;
			try {
				// Create the off-line device
				OfflinePacketDevice selectedDevice = new OfflinePacketDevice(file);

				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
				// Compile the filter
				using (BerkeleyPacketFilter filter =
					communicator.CreateFilter(SnifferConfig.Filter.FilterString)) {
					communicator.SetFilter(filter);
				}

				// Read and dispatch packets until EOF is reached
				communicator.ReceivePackets(0, callback);
			}
			catch (Exception) {
				IsBadDumpFile = true;
			}
			finally {
				if (pc != null)
					communicator = pc;
			}

		}
예제 #35
0
            //public Packet CreateDhcpPacket(int optionsSize, byte[] options, bool firstPacket, byte[] clientIp = null)
            //{
            //    EthernetLayer ethernetLayer = new EthernetLayer
            //    {
            //        Source = ifHardwareAddress,
            //        Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //        EtherType = EthernetType.None,
            //    };

            //    IpV4Layer ipV4Layer = new IpV4Layer
            //    {
            //        Source = new IpV4Address("0.0.0.0"),
            //        CurrentDestination = new IpV4Address("255.255.255.255"),
            //        Fragmentation = IpV4Fragmentation.None,
            //        HeaderChecksum = null, // Will be filled automatically.
            //        Identification = ipID,
            //        Options = IpV4Options.None,
            //        Protocol = null,
            //        Ttl = 128,
            //        TypeOfService = 0,
            //    };

            //    UdpLayer udpLayer = new UdpLayer
            //    {
            //        SourcePort = 68,
            //        DestinationPort = 67,
            //        Checksum = null, // Will be filled automatically.
            //        CalculateChecksumValue = true,
            //    };

            //    Dhcp dhcpLayer = new Dhcp(optionsSize);
            //    if (firstPacket)
            //        dhcpId = dhcpLayer.Id;
            //    else
            //        dhcpLayer.Id = dhcpId;
            //    if (clientIp != null)
            //        dhcpLayer.ClientIp = clientIp;
            //    dhcpLayer.ClientHardwareAddress = ifHardwareAddressByte;
            //    dhcpLayer.Options = options;


            //    PayloadLayer payloadLayer = new PayloadLayer
            //    {
            //        Data = new Datagram(dhcpLayer.toByteArray()),
            //    };

            //    PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);
            //    return builder.Build(DateTime.Now);
            //}
            //public void SendArp()
            //{
            //    EthernetLayer ethernetLayer = new EthernetLayer
            //    {
            //        Source = ifHardwareAddress,
            //        Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //        EtherType = EthernetType.None,
            //    };

            //    ArpLayer arpLayer = new ArpLayer
            //    {
            //        ProtocolType = EthernetType.IpV4,
            //        Operation = ArpOperation.Request,
            //        SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //        SenderProtocolAddress = ownProtocolAddressByte.AsReadOnly(),
            //        TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //        TargetProtocolAddress = gatewayProtocolAddressByte.AsReadOnly(),
            //    };

            //    PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //    SendPacket(builder.Build(DateTime.Now));
            //}
            //public void ReceiveIpAddress()
            //{
            //    int retries = 0;
            //    int timewait = 0;
            //    dhcpState = 0;
            //    arpState = 0;

            //    byte[] options;
            //    while (true)
            //    {
            //        if (dhcpState == 1 && retries > 1 ||
            //            dhcpState == 3 && retries > 1)
            //        {
            //            dhcpState = 6;
            //            offeredIp = BitConverter.GetBytes(ifProtocolAddress.ToValue() & ifProtocolMask.ToValue() + 1).Reverse().ToArray();
            //        }
            //        if (dhcpState == 0 || dhcpState == 1 && timewait > 10)
            //        {
            //            options = new byte[]
            //        { 
            //            53, 1, 1,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            12, 4, 78, 77, 76, 66,
            //            60, 8, 0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30,
            //            255,
            //            0, 0, 0,
            //        };
            //            SendPacket(CreateDhcpPacket(32, options, true));
            //            if (dhcpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            dhcpState = 1;
            //        }
            //        else if (dhcpState == 2 || dhcpState == 3 && timewait > 10)
            //        {
            //            options = new byte[]
            //        { 
            //            53, 1, 3,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            12, 4, 78, 77, 76, 66,
            //            50, 4, offeredIp[0], offeredIp[1], offeredIp[2], offeredIp[3],
            //            54, 4, dhcpServer[0], dhcpServer[1], dhcpServer[2], dhcpServer[3],
            //            60, 8, 0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30,
            //            255,
            //            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            //        };
            //            SendPacket(CreateDhcpPacket(60, options, false));
            //            if (dhcpState == 2)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            dhcpState = 3;
            //        }
            //        else if (dhcpState == 4 && arpState == 1 && retries > 1)
            //        {
            //            if ((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1 & ifProtocolMask.ToValue()) !=
            //                (ifProtocolAddress.ToValue() & ifProtocolMask.ToValue()))
            //            {
            //                Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " is in a different network!");
            //                offeredIp = BitConverter.GetBytes(ifProtocolAddress.ToValue() & ifProtocolMask.ToValue() + 1).Reverse().ToArray();
            //                dhcpState = 6;
            //                arpState = 0;
            //                continue;
            //            }
            //            dhcpState = 5;
            //            arpState = 0;
            //            Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " OK!");
            //            dhcpClientId++;
            //            ownProtocolAddressByte = offeredIp;
            //            ownProtocolAddressString = ownProtocolAddressByte.SequenceToString(".");
            //            ownProtocolAddress = new IpV4Address(ownProtocolAddressString);
            //            SendArp();
            //            break;
            //        }
            //        else if (dhcpState == 4 && arpState == 0 || dhcpState == 4 && arpState == 1 && timewait > 10)
            //        {
            //            EthernetLayer ethernetLayer = new EthernetLayer
            //            {
            //                Source = ifHardwareAddress,
            //                Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //                EtherType = EthernetType.None,
            //            };

            //            ArpLayer arpLayer = new ArpLayer
            //            {
            //                ProtocolType = EthernetType.IpV4,
            //                Operation = ArpOperation.Request,
            //                SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //                SenderProtocolAddress = new byte[] { 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetProtocolAddress = offeredIp.AsReadOnly(),
            //            };

            //            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //            SendPacket(builder.Build(DateTime.Now));
            //            if (arpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            arpState = 1;
            //        }
            //        else if (dhcpState == 4 && arpState == 2)
            //        {
            //            Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " is already used!");
            //            options = new byte[]
            //        { 
            //            53, 1, 4,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            50, 4, offeredIp[0], offeredIp[1], offeredIp[2], offeredIp[3],
            //            54, 4, dhcpServer[0], dhcpServer[1], dhcpServer[2], dhcpServer[3],
            //            255,
            //            //0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            //        };
            //            SendPacket(CreateDhcpPacket(25, options, false, offeredIp));
            //            arpState = 0;
            //            dhcpState = 0;
            //        }
            //        else if (dhcpState == 6 && arpState == 1 && retries > 1)
            //        {
            //            dhcpState = 5;
            //            arpState = 0;
            //            Global.WriteLog("IPAlloc: IP " + offeredIp.SequenceToString(".") + " OK!");
            //            dhcpClientId++;
            //            ownProtocolAddressByte = offeredIp;
            //            ownProtocolAddressString = ownProtocolAddressByte.SequenceToString(".");
            //            ownProtocolAddress = new IpV4Address(ownProtocolAddressString);
            //            SendArp();
            //            break;
            //        }
            //        else if (dhcpState == 6 && arpState == 0 || dhcpState == 6 && arpState == 1 && timewait > 10)
            //        {
            //            EthernetLayer ethernetLayer = new EthernetLayer
            //            {
            //                Source = ifHardwareAddress,
            //                Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //                EtherType = EthernetType.None,
            //            };

            //            ArpLayer arpLayer = new ArpLayer
            //            {
            //                ProtocolType = EthernetType.IpV4,
            //                Operation = ArpOperation.Request,
            //                SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //                SenderProtocolAddress = new byte[] { 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetProtocolAddress = offeredIp.AsReadOnly(),
            //            };

            //            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //            SendPacket(builder.Build(DateTime.Now));
            //            if (arpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            arpState = 1;
            //        }
            //        else if (dhcpState == 6 && arpState == 2)
            //        {
            //            if ((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1 & ifProtocolMask.ToValue()) !=
            //                (ifProtocolAddress.ToValue() & ifProtocolMask.ToValue()))
            //            {
            //                Global.WriteLog("IPAlloc: Couldn't allocate IP address!");
            //                break;
            //            }
            //            Global.WriteLog("IPAlloc: IP " + offeredIp.SequenceToString(".") + " is already used!");
            //            offeredIp = BitConverter.GetBytes((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1)).Reverse().ToArray();
            //            arpState = 0;
            //        }
            //        Thread.Sleep(100);
            //        timewait++;
            //    }
            //}

            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the interface
                PacketDevice selectedDevice = null;
                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.ToUpper().Contains(Guid.ToString().ToUpper()))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Load Balancer", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Load Balancer: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Load Balancer: Listening on " + Name + "...");
                        //communicator.SetFilter("(ether dst " + ifHardwareAddressString + " and (ip or arp)) or (ether dst FF:FF:FF:FF:FF:FF and arp)");
                        communicator.SetFilter("(ether dst " + ifHardwareAddressString + " and ip and (udp or icmp))");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!ThreadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            //if (ownProtocolAddressString == null)
                            //{
                            //    if (packet.Ethernet.IpV4.Udp.SourcePort == 67 && packet.Ethernet.IpV4.Udp.DestinationPort == 68 && (PublicVars.dhcpState == 1 || PublicVars.dhcpState == 3))
                            //    {
                            //        Dhcp dhcpReply = new Dhcp(packet.Ethernet.IpV4.Udp.Payload.ToArray());
                            //        if (PublicVars.dhcpId == dhcpReply.Id && dhcpReply.MessageType == 2)
                            //        {
                            //            if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 2)
                            //            {
                            //                PublicVars.offeredIp = dhcpReply.YourIp;
                            //                PublicVars.dhcpServer = dhcpReply.getOption((int)DhcpOptionCode.DhcpServerId);
                            //                PublicVars.dhcpState = 2;
                            //            }
                            //            else if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 5)
                            //            {
                            //                PublicVars.dhcpState = 4;
                            //            }
                            //            else if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 6)
                            //            {
                            //                PublicVars.offeredIp = null;
                            //                PublicVars.dhcpState = 0;
                            //                PublicVars.dhcpId = 0;
                            //            }
                            //        }
                            //    }
                            //    else if (packet.Ethernet.EtherType == EthernetType.Arp && PublicVars.arpState == 1)
                            //    {
                            //        if (packet.Ethernet.Arp.SenderProtocolAddress.SequenceEqual(PublicVars.offeredIp))
                            //            PublicVars.arpState = 2;
                            //    }
                            //}
                            //if (packet.Ethernet.EtherType == EthernetType.Arp)
                            //{
                            //    if (packet.Ethernet.Arp.TargetProtocolAddress.SequenceEqual(ownProtocolAddressByte) &&
                            //        packet.Ethernet.Arp.Operation == ArpOperation.Request)
                            //    {
                            //        EthernetLayer ethernetLayer = new EthernetLayer
                            //        {
                            //            Source = ifHardwareAddress,
                            //            Destination = packet.Ethernet.Source,
                            //            EtherType = EthernetType.None,
                            //        };

                            //        ArpLayer arpLayer = new ArpLayer
                            //        {
                            //            ProtocolType = EthernetType.IpV4,
                            //            Operation = ArpOperation.Reply,
                            //            SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
                            //            SenderProtocolAddress = packet.Ethernet.Arp.TargetProtocolAddress,
                            //            TargetHardwareAddress = packet.Ethernet.Arp.SenderHardwareAddress,
                            //            TargetProtocolAddress = packet.Ethernet.Arp.SenderProtocolAddress,
                            //        };

                            //        PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
                            //        communicator.SendPacket(builder.Build(DateTime.Now));
                            //    }
                            //}
                            if (tapWorker.Initialized.IsSet)
                            {
                                if (packet.Ethernet.IpV4.Length > MTU) // only UDP and ICMP
                                {
                                    EthernetLayer ethernetLayer = new EthernetLayer
                                    {
                                        Source = ifHardwareAddress,
                                        Destination = packet.Ethernet.Source,
                                        EtherType = EthernetType.None,
                                    };
                                    IpV4Layer ipV4Layer = new IpV4Layer
                                    {
                                        Source = packet.Ethernet.IpV4.Destination,
                                        CurrentDestination = packet.Ethernet.IpV4.Source,
                                        Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                        HeaderChecksum = null, // Will be filled automatically.
                                        Identification = 123,
                                        Options = packet.Ethernet.IpV4.Options,
                                        Protocol = packet.Ethernet.IpV4.Protocol,
                                        Ttl = packet.Ethernet.IpV4.Ttl,
                                        TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                    };
                                    IcmpDestinationUnreachableLayer icmpLayer = new IcmpDestinationUnreachableLayer
                                    {
                                        Code = IcmpCodeDestinationUnreachable.FragmentationNeededAndDoNotFragmentSet,
                                        NextHopMaximumTransmissionUnit = (ushort)MTU,
                                    };

                                    PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);
                                    SendPacket(builder.Build(DateTime.Now));
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                        Global.ShowTrayTip("Load Balancer", "IP packet larger than the MTU detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    Global.WriteLog("Load Balancer: IP packet larger than the MTU detected on " + Name);
                                    return;
                                }
                                if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment ||
                                packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0)
                                {
                                    if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.InternetControlMessageProtocol)
                                    {

                                        if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                            if ((packet.Ethernet.IpV4.Icmp.MessageType == IcmpMessageType.EchoReply || packet.Ethernet.IpV4.Fragmentation.Offset > 0))
                                            {
                                                EthernetLayer ethernetLayer = new EthernetLayer
                                                {
                                                    Source = tapWorker.ownHardwareAddress,
                                                    Destination = tapWorker.ifHardwareAddress,
                                                    EtherType = EthernetType.None,
                                                };
                                                IpV4Layer ipV4Layer = new IpV4Layer
                                                {
                                                    Source = packet.Ethernet.IpV4.Source,
                                                    CurrentDestination = tapWorker.ifProtocolAddress,
                                                    Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                                    HeaderChecksum = null, // Will be filled automatically.
                                                    Identification = packet.Ethernet.IpV4.Identification,
                                                    Options = packet.Ethernet.IpV4.Options,
                                                    Protocol = packet.Ethernet.IpV4.Protocol,
                                                    Ttl = packet.Ethernet.IpV4.Ttl,
                                                    TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                                };
                                                PayloadLayer payloadLayer = new PayloadLayer
                                                {
                                                    Data = new Datagram(packet.Ethernet.IpV4.Payload.ToArray()),
                                                };
                                                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);
                                                tapWorker.SendPacket(builder.Build(DateTime.Now));
                                            }
                                    }
                                    //else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
                                    //{
                                    //    if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                    //    {
                                    //        lock (RoutingTable.lockObj)
                                    //            routingObject = RoutingTable.TranslateBack(packet);
                                    //        if (routingObject.ifIndex == -1)
                                    //            return;
                                    //        EthernetLayer ethernetLayer = new EthernetLayer
                                    //        {
                                    //            Source = TapWorker.ownHardwareAddress,
                                    //            Destination = TapWorker.ifHardwareAddress,
                                    //            EtherType = packet.Ethernet.EtherType,
                                    //        };
                                    //        IpV4Layer ipV4Layer = new IpV4Layer
                                    //        {
                                    //            Source = packet.Ethernet.IpV4.Source,
                                    //            CurrentDestination = TapWorker.ifProtocolAddress,
                                    //            Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                    //            HeaderChecksum = null, // Will be filled automatically.
                                    //            Identification = packet.Ethernet.IpV4.Identification,
                                    //            Options = packet.Ethernet.IpV4.Options,
                                    //            Protocol = packet.Ethernet.IpV4.Protocol,
                                    //            Ttl = packet.Ethernet.IpV4.Ttl,
                                    //            TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                    //        };
                                    //        TcpLayer tcpLayer = new TcpLayer
                                    //        {
                                    //            SourcePort = packet.Ethernet.IpV4.Tcp.SourcePort,
                                    //            DestinationPort = routingObject.localPort,
                                    //            Checksum = null, // Will be filled automatically.
                                    //            SequenceNumber = packet.Ethernet.IpV4.Tcp.SequenceNumber,
                                    //            AcknowledgmentNumber = routingObject.ack,
                                    //            ControlBits = packet.Ethernet.IpV4.Tcp.ControlBits,
                                    //            Window = packet.Ethernet.IpV4.Tcp.Window,
                                    //            UrgentPointer = packet.Ethernet.IpV4.Tcp.UrgentPointer,
                                    //            Options = packet.Ethernet.IpV4.Tcp.Options,
                                    //        };
                                    //        PayloadLayer payloadLayer = new PayloadLayer
                                    //        {
                                    //            Data = new Datagram(packet.Ethernet.IpV4.Tcp.Payload.ToArray()),
                                    //        };
                                    //        PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);
                                    //        MainThread.tapWorker.SendPacket(builder.Build(DateTime.Now));
                                    //    }
                                    //}
                                    else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
                                    {
                                        if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                        {
                                            phyRoutingObject = RoutingTable.IsUdpConn(packet);
                                            if (phyRoutingObject.ifIndex == -1)
                                                return;
                                            EthernetLayer ethernetLayer = new EthernetLayer
                                            {
                                                Source = tapWorker.ownHardwareAddress,
                                                Destination = tapWorker.ifHardwareAddress,
                                                EtherType = packet.Ethernet.EtherType,
                                            };
                                            IpV4Layer ipV4Layer = new IpV4Layer
                                            {
                                                Source = packet.Ethernet.IpV4.Source,
                                                CurrentDestination = tapWorker.ifProtocolAddress,
                                                Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                                HeaderChecksum = null, // Will be filled automatically.
                                                Identification = packet.Ethernet.IpV4.Identification,
                                                Options = packet.Ethernet.IpV4.Options,
                                                Protocol = packet.Ethernet.IpV4.Protocol,
                                                Ttl = packet.Ethernet.IpV4.Ttl,
                                                TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                            };
                                            UdpLayer udpLayer = new UdpLayer
                                            {
                                                SourcePort = packet.Ethernet.IpV4.Udp.SourcePort,
                                                DestinationPort = packet.Ethernet.IpV4.Udp.DestinationPort,
                                                Checksum = null, // Will be filled automatically.
                                                CalculateChecksumValue = packet.Ethernet.IpV4.Udp.IsChecksumOptional,
                                            };
                                            PayloadLayer payloadLayer = new PayloadLayer
                                            {
                                                Data = new Datagram(packet.Ethernet.IpV4.Udp.Payload.ToArray()),
                                            };
                                            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);
                                            tapWorker.SendPacket(builder.Build(DateTime.Now));
                                        }
                                    }
                                }
                                else if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset > 0)
                                {
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                        Global.ShowTrayTip("Load Balancer", "IP fragmentation detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    Global.WriteLog("Load Balancer: IP fragmentation detected on " + Name);
                                    //fragments = fragBuffer.Add(packet);
                                    //if (fragments != null)
                                    //    for (int i = 0; i < fragments.Count; i++)
                                    //    {
                                    //        IpV4Handler(fragments[i], fragments);
                                    //    }
                                }
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    if (ThreadActive.IsSet)
                    {
                        ThreadActive.Reset();
                        Global.WriteLog("Load Balancer: " + Name + " has disconnected");
                        if (Global.Config.Gadget.Debug)
                            Global.WriteLog(e.ToString());
                        Global.ShowTrayTip("Load Balancer", Name + " has disconnected", System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
예제 #36
0
        public static void Test_CapturingThePackets_01()
        {
            // from project OpeningAnAdapterAndCapturingThePackets
            _tr.WriteLine("Test_CapturingThePackets_01");
            //rpcap://\Device\NPF_{BF8A52CB-F023-4F24-AA7E-958A8D1F3069}
            //IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
            //string deviceName = @"rpcap://\Device\NPF_{BF8A52CB-F023-4F24-AA7E-958A8D1F3069}";
            //_tr.WriteLine("select device \"{0}\"", deviceName);
            //PacketDevice device = (from d in LivePacketDevice.AllLocalMachine where d.Name == deviceName select d).FirstOrDefault();
            //if (device == null)
            //{
            //    _tr.WriteLine("device not found");
            //    return;
            //}

            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))
                {
                    _tr.WriteLine("Listening on " + device.Description + "...");
                    // start the capture
                    __communicator.ReceivePackets(0, CapturingPacketHandler);
                }
            }
            catch (Exception ex)
            {
                _tr.WriteLine(ex.Message);
            }
            finally
            {
                //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution);
            }
        }
예제 #37
0
        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);
            }
        }
예제 #38
0
        public static void Test_ReadPacketsFromDumpFile_01()
        {
            // from project ReadingPacketsFromADumpFile
            _tr.WriteLine("Test_ReadPacketsFromDumpFile_01");

            string dumpFile = @"dump\dump.pcap";
            dumpFile = GetPath(dumpFile);
            _tr.WriteLine("read packets from dump file \"{0}\"", dumpFile);

            // Create the offline device
            OfflinePacketDevice device = new OfflinePacketDevice(dumpFile);

            __communicator = null;
            //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution);
            _rs.OnAbortExecution = OnAbortExecution;
            try
            {
                // Open the capture file
                using (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Read and dispatch packets until EOF is reached
                    __communicator.ReceivePackets(0, ReadPacketsFromDumpFile);
                }
            }
            finally
            {
                //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution);
            }
        }
예제 #39
0
        public static void Test_InterpretingThePackets_01()
        {
            // from project InterpretingThePackets
            _tr.WriteLine("Test_InterpretingThePackets_01");
            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))
                {
                    // Check the link layer. We support only Ethernet for simplicity.
                    if (__communicator.DataLink.Kind != DataLinkKind.Ethernet)
                    {
                        _tr.WriteLine("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);
                    }

                    _tr.WriteLine("Listening on " + device.Description + "...");

                    // start the capture
                    __communicator.ReceivePackets(0, InterpretingPacketHandler);
                }
            }
            catch (Exception ex)
            {
                _tr.WriteLine(ex.Message);
            }
            finally
            {
                //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution);
            }
        }