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);
            }
        }
        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);
            }
        }
        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 = "监听已启动";
                }));
            });
        }
Esempio n. 4
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;
        }
Esempio n. 5
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;
                }
            }
        }
Esempio n. 6
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;
                }
            }
        }
Esempio n. 7
0
            public void StartCapture()
            {
                // portion of the packet to capture
                // 65536 guarantees that the whole packet will be captured on all the link layers
                var snapshotLength = 65536;

                // promiscuous mode
                var packetDeviceOpenAttributes = PacketDeviceOpenAttributes.Promiscuous;

                // read timeout
                var timeout = 1000;

                this._PacketCommunicator?.Break();
                this._PacketCommunicator?.Dispose();
                this._PacketCommunicator = this._Device.Open(snapshotLength, packetDeviceOpenAttributes, timeout);

                this._Filter?.Dispose();

                this._Filter = this._PacketCommunicator.CreateFilter("ip and tcp and port http");
                this._PacketCommunicator.SetFilter(this._Filter);

                this._Task?.Dispose();
                this._Task = Task.Run(() =>
                {
                    try
                    {
                        // 停止時に例外を投げるが、原因不明
                        this._PacketCommunicator.ReceivePackets(0, this.OnPacketReceived);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                });
            }
        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);
            }
        }
Esempio n. 9
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();
                }
            }
        }
 public void TestNullTest()
 {
     using (BerkeleyPacketFilter filter = new BerkeleyPacketFilter("ether src 11:22:33:44:55:66", PacketDevice.DefaultSnapshotLength, DataLinkKind.Ethernet))
     {
         filter.Test(null);
     }
     Assert.Fail();
 }
 public void TestNullTest()
 {
     using (BerkeleyPacketFilter filter = new BerkeleyPacketFilter("ether src 11:22:33:44:55:66", PacketDevice.DefaultSnapshotLength, DataLinkKind.Ethernet))
     {
         filter.Test(null);
     }
     Assert.Fail();
 }
Esempio n. 12
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();
            }
        }
Esempio n. 13
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);
            }
        }
Esempio n. 14
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            IPDict = new Dictionary <IpV4Address, int>();

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

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

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

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

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

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

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


                    //****************************** ARP Paket dinleme ******************************
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("arp")) // Filtre uygulandı.
                    {
                        communicator.SetFilter(filter);
                    }
                    Packet packet;
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Ok:
                        if (!listBox1.Items.Contains(packet.Ethernet.Source + "\t\t\t@" + packet.Ethernet.Arp.SenderProtocolIpV4Address.ToString())) // Listbox'da oluşabilecek veri tekrarı önlendi.
                        {
                            listBox1.Items.Add(packet.Ethernet.Source + "\t\t\t@" + packet.Ethernet.Arp.SenderProtocolIpV4Address.ToString());       // Gelen Arp Paketlerinin Ethernet Katmanındna Source MAC Addres verisi çekildi.
                        }
                        break;
                    }
                }
            }
        }
Esempio n. 16
0
            public void StopCapture()
            {
                this._PacketCommunicator?.Break();
                this._PacketCommunicator?.Dispose();
                this._Filter?.Dispose();

                this._PacketCommunicator = null;
                this._Filter             = null;
            }
Esempio n. 17
0
        public void StartReceivingArpPackets()
        {
            // Set "arp reply" filter
            using (BerkeleyPacketFilter filter = this.arpScanConfig.Communicator.CreateFilter("arp and arp[6:2] = 2"))
            {
                this.arpScanConfig.Communicator.SetFilter(filter);
            }

            this.arpScanConfig.Communicator.ReceivePackets(0, this.PacketHandler);
        }
Esempio n. 18
0
 private void toolStripButton1_Click(object sender, EventArgs e)
 {
     using (PacketCommunicator communicator = selectedAdapter.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
     {
         using (BerkeleyPacketFilter filter = communicator.CreateFilter(tbFilter.Text))
         {
             // Set the filter
             communicator.SetFilter(filter);
         }
     }
 }
Esempio n. 19
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);
        }
Esempio n. 20
0
        private static 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,
                                                   PacketDeviceOpenAttributes.Promiscuous,
                                                   1000))
                    {
                        // Compile the filter
                        using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp and port 5056")) // Restrict to only photon event port
                        {
                            // Set the filter
                            communicator.SetFilter(filter);
                        }

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

                        // start the capture
                        communicator.ReceivePackets(0, photonPacketHandler.PacketHandler);
                    }
                });
                // Make sure thread closes on application exit
                t.IsBackground = true;
                t.Start();
            }
        }
Esempio n. 21
0
        private static void InterceptDevice(object data)
        {
            LivePacketDevice device = (LivePacketDevice)data;

            using (PacketCommunicator communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                using (BerkeleyPacketFilter filter = communicator.CreateFilter("udp port 14001"))
                {
                    communicator.SetFilter(filter);
                    communicator.ReceivePackets(int.MaxValue, PacketHandler);
                }
            }
        }
Esempio n. 22
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);
            }
        }
Esempio n. 23
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.");
                ctx.Channel.SendMessageAsync("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;
                    new Thread(delegate()
                    {
                        using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                        {
                            if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                            {
                                Debug.WriteLine("This program works only on Ethernet networks.");
                                ctx.Channel.SendMessageAsync("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));
                            }
                        }
                    }).Start();
                }
            }
        }
Esempio n. 24
0
 public void captureCDP()
 {
     try
     {
         using (BerkeleyPacketFilter filter = communicator.CreateFilter("ether host 01:00:0c:cc:cc:cc and ether[16:4] = 0x0300000C and ether[20:2] == 0x2000"))
         {
             communicator.SetFilter(filter);
         }
         communicator.NonBlocking = false;
         communicator.ReceivePackets(1, PacketHandler);
     }
     catch (Exception)
     {
     }
 }
Esempio n. 25
0
        private void OpenDevice(PacketDevice selectedDevice)
        {
            // Open the device
            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,
                                           PacketDeviceOpenAttributes.MaximumResponsiveness,
                                           1000))
            {
                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                {
                    MessageHelper.PrintMessage("This program works only on Ethernet networks.");
                    return;
                }

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

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

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

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

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

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

                repo.SaveMonitoringResultsToTextFile(FileLocation);
            }
        }
Esempio n. 26
0
        // modified code from: https://github.com/PcapDotNet/Pcap.Net/wiki/Pcap.Net-Tutorial-Interpreting-the-packets
        // used in the first part of packet sniffing
        public void SniffPackets(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
            {
                // Compile the filter
                using (BerkeleyPacketFilter filter = communicator.CreateFilter(""))
                    communicator.SetFilter(filter);

                // start the capture
                communicator.ReceivePackets(0, PacketHandler);
            }
        }
Esempio n. 27
0
        public void NoCommunicatorConstructorWithNetmaskTest()
        {
            const string SourceMac = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            Random random = new Random();
            Packet expectedPacket = random.NextEthernetPacket(1000, SourceMac, DestinationMac);
            Packet unexpectedPacket = random.NextEthernetPacket(1000, DestinationMac, SourceMac);

            using (PacketCommunicator communicator = LivePacketDeviceTests.OpenLiveDevice())
            {
                using (BerkeleyPacketFilter filter = new BerkeleyPacketFilter("ether src " + SourceMac + " and ether dst " + DestinationMac, 1000, DataLinkKind.Ethernet, communicator.IpV4Netmask))
                {
                    TestFilter(communicator, filter, expectedPacket, unexpectedPacket);
                }
            }
        }
        public void NoCommunicatorConstructorWithNetmaskTest()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            Random random           = new Random();
            Packet expectedPacket   = random.NextEthernetPacket(1000, SourceMac, DestinationMac);
            Packet unexpectedPacket = random.NextEthernetPacket(1000, DestinationMac, SourceMac);

            using (PacketCommunicator communicator = LivePacketDeviceTests.OpenLiveDevice())
            {
                using (BerkeleyPacketFilter filter = new BerkeleyPacketFilter("ether src " + SourceMac + " and ether dst " + DestinationMac, 1000, DataLinkKind.Ethernet, communicator.IpV4Netmask))
                {
                    TestFilter(communicator, filter, expectedPacket, unexpectedPacket);
                }
            }
        }
Esempio n. 29
0
        private void button4_Click(object sender, EventArgs e)
        {
            int selectedIndex = this.comboBoxNetworkAdapter.SelectedIndex;

            if (selectedIndex >= 0 && selectedIndex <= (this._networkAdapters.Count - 1))
            {
                DisableLivePcapParsingButton();
                DisablePcapButton();
                labelCapturingIndication.Visible = true;
                comboBoxNetworkAdapter.Enabled   = false;
                Task.Factory.StartNew(() =>
                {
                    LivePacketDevice selectedDevice = this._networkAdapters[selectedIndex];
                    // 65536 guarantees that the whole packet will be captured on all the link layers
                    using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                    {
                        using (BerkeleyPacketFilter filter = communicator.CreateFilter("tcp dst port 9295 or tcp src port 9295"))
                        {
                            // Set the filter
                            communicator.SetFilter(filter);
                        }

                        // start the capture
                        communicator.ReceivePackets(0, PacketHandlerTcp);
                    }
                });
                Task.Factory.StartNew(() =>
                {
                    LivePacketDevice selectedDevice = this._networkAdapters[selectedIndex];

                    // 65536 guarantees that the whole packet will be captured on all the link layers
                    using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                    {
                        using (BerkeleyPacketFilter filter = communicator.CreateFilter("udp dst port 9296 or udp src port 9296"))
                        {
                            // Set the filter
                            communicator.SetFilter(filter);
                        }

                        // start the capture
                        communicator.ReceivePackets(0, PacketHandlerUdp);
                    }
                });
            }
        }
Esempio n. 30
0
        private void ListenForArps()
        {
            using (
                PacketCommunicator communicator = frmCapture.myDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous,
                                                                           1000))
            {
                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                {
                    MessageBox.Show("Ethernet Only");
                }
                using (BerkeleyPacketFilter filter = communicator.CreateFilter("arp"))
                {
                    communicator.SetFilter(filter);
                }

                communicator.ReceivePackets(0, PacketHandler);
            }
        }
Esempio n. 31
0
        public void Dinle()
        {
            using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                {
                    Console.WriteLine("This program works only on Ethernet networks.");
                    return;
                }

                using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip"))
                {
                    communicator.SetFilter(filter);
                }

                communicator.ReceivePackets(0, PacketHandler);
            }
        }
Esempio n. 32
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            using (PacketCommunicator communicator = selectedAdapter.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                // Check the link layer.
                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                {
                    MessageBox.Show("This program works only on Ethernet networks!");

                    return;
                }


                //Deallocation is  necessary
                if (_tcp.Checked && (!_udp.Checked))//just tcp
                {
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("tcp"))
                    {
                        // Set the filter
                        communicator.SetFilter(filter);
                    }
                }

                else if (_udp.Checked && !(_tcp.Checked))//just udp
                {
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("udp"))
                    {
                        // Set the filter
                        communicator.SetFilter(filter);
                    }
                }

                else if (_tcp.Checked && (_udp.Checked))//tcp and udp
                {
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp"))
                    {
                        // Set the filter
                        communicator.SetFilter(filter);
                    }
                }
                // Begin the capture
                communicator.ReceivePackets(0, PacketHandler);
            }
        }
Esempio n. 33
0
        private static void TestFilter(PacketCommunicator communicator, BerkeleyPacketFilter filter, Packet expectedPacket, Packet unexpectedPacket)
        {
            communicator.SetFilter(filter);
            for (int i = 0; i != 5; ++i)
            {
                communicator.SendPacket(expectedPacket);
                communicator.SendPacket(unexpectedPacket);
            }

            Packet packet;
            PacketCommunicatorReceiveResult result;
            for (int i = 0; i != 5; ++i)
            {
                result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                Assert.AreEqual(expectedPacket, packet);
            }

            result = communicator.ReceivePacket(out packet);
            Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result);
            Assert.IsNull(packet);
        }
Esempio n. 34
0
        public void TestTest()
        {
            const string SourceMac = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";
            const int SnapshotLength = 500;

            Random random = new Random();

            using (BerkeleyPacketFilter filter = new BerkeleyPacketFilter("ether src " + SourceMac + " and ether dst " + DestinationMac, SnapshotLength, DataLinkKind.Ethernet))
            {
                Assert.IsTrue(filter.Test(random.NextEthernetPacket(SnapshotLength / 2, SourceMac, DestinationMac)));
                Assert.IsTrue(filter.Test(random.NextEthernetPacket(SnapshotLength - 1, SourceMac, DestinationMac)));
                Assert.IsTrue(filter.Test(random.NextEthernetPacket(SnapshotLength, SourceMac, DestinationMac)));
                Assert.IsTrue(filter.Test(random.NextEthernetPacket(SnapshotLength + 1, SourceMac, DestinationMac)));
                Assert.IsTrue(filter.Test(random.NextEthernetPacket(SnapshotLength * 2, SourceMac, DestinationMac)));

                Assert.IsFalse(filter.Test(random.NextEthernetPacket(SnapshotLength / 2, DestinationMac, SourceMac)));

                int actualSnapshotLength;
                Assert.IsTrue(filter.Test(out actualSnapshotLength, random.NextEthernetPacket(SnapshotLength / 2, SourceMac, DestinationMac)));
                Assert.AreEqual(SnapshotLength, actualSnapshotLength);
            }
        }