Beispiel #1
0
 private void BtnStop_Click(object sender, EventArgs e)
 {
     if (btnCapture.Enabled == false)
     {
         _device.StopCapture();
         _device.Close();
         btnCapture.Enabled    = true;
         btnStop.Enabled       = false;
         cboInterfaces.Enabled = true;
     }
 }
Beispiel #2
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (CaptureLaunched == true)
     {
         button1.Text = "Stopping...";
         try
         {
             device.StopCapture();
         }
         catch { }
         device.Close();
         button1.Text = "START";
         CaptureLaunched = false;
         comboBox1.Enabled = true;
     }
     else if (CaptureLaunched == false)
     {
         button1.Text = "Starting...";
         device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
         int readTimeoutMilliseconds = 1000;
         device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
         device.StartCapture();
         button1.Text = "STOP";
         CaptureLaunched = true;
         comboBox1.Enabled = false;
     }
 }
Beispiel #3
0
        public async Task Run()
        {
            try
            {
                string interfaceDesc = "Network adapter 'Intel(R) Ethernet Connection (2) I219-V' on local host";

                ICaptureDevice device = CaptureDeviceList.Instance.Where(x => x.Description == interfaceDesc).FirstOrDefault();
                string         name   = device.Name;
                string         desc   = device.Description;


                device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(HandlePacket);
                device.Open(DeviceMode.Promiscuous, 30000);
                device.Filter = "tcp port 43594 || 43595";


                device.StartCapture();

                Console.ReadLine();

                device.StopCapture();
                device.Close();
            }
            catch (Exception ex)
            {
            }
        }
        public void BeginCapture(BackgroundWorker worker, ICaptureDevice networkDevice)
        {
            networkDevice.Open(DeviceMode.Promiscuous, 1000);

            while (!worker.CancellationPending)
            {
                var rawPackage = networkDevice.GetNextPacket();
                if (rawPackage == null)
                {
                    continue;
                }

                var packet   = Packet.ParsePacket(rawPackage.LinkLayerType, rawPackage.Data);
                var ipPacket = (IpPacket)packet.Extract(typeof(IpPacket));

                if (ipPacket == null)
                {
                    continue;
                }

                PackageGenerated(new PackageGeneratedArgs()
                {
                    GeneratedPackage = ipPacket.Protocol == IPProtocolType.TCP ?
                                       new TCPPackage(ipPacket) :
                                       new Package(ipPacket)
                });
            }

            networkDevice.StopCapture();
            networkDevice.Close();
        }
Beispiel #5
0
        private void btnSendPacket_Click(object sender, RoutedEventArgs e)
        {
            device = gbxDevInfo.DataContext as ICaptureDevice;
            // Open the device
            device.Open();


            try
            {
                IPAddress  ip        = IPAddress.Parse(tbxSourceIp.Text);
                IPAddress  ipaddress = System.Net.IPAddress.Parse(tbxDestinationIp.Text);
                TcpPacket  tcpPakje  = new TcpPacket(80, 80);
                IPv4Packet pakje     = new IPv4Packet(ip, ipaddress);
                pakje.PayloadData = System.Text.Encoding.ASCII.GetBytes(tbxPayloadIp.Text);
                pakje.TimeToLive  = int.Parse(tbxTTLIp.Text);
                // pakje.Protocol = tbxProtocolIp.Text;
                device.SendPacket(pakje);
                Console.WriteLine("-- Packet sent successfuly.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("-- " + ex.Message);
            }

            // Close the pcap device
            device.Close();
            Console.WriteLine("-- Device closed.");
        }
Beispiel #6
0
        private void CreateListener()
        {
            var allDevices = CaptureDeviceList.Instance;

            if (allDevices.Count == 0)
            {
                log.Debug("No Network Interface Found! Please make sure WinPcap is properly installed.");
                return;
            }
            for (int i = 0; i != allDevices.Count; i++)
            {
                ICaptureDevice device = allDevices[i];

                if (device.Description != null)
                {
                    Debug.WriteLine(" (" + device.Description + ")");
                }
                else
                {
                    Debug.WriteLine(" (Unknown)");
                }

                device.OnPacketArrival += new PacketArrivalEventHandler(PacketHandle);
                device.Open(DeviceMode.Promiscuous, 1000);
                device.Filter = "ip and udp and (port 5056 or port 5055 or port 4535)";
                if (device.LinkType != LinkLayers.Ethernet)
                {
                    device.Close();
                    continue;
                }
                device.StartCapture();
            }
        }
Beispiel #7
0
        /// <summary>
        /// IEnumerable helper allows for easy foreach usage, extension method and Linq usage
        /// </summary>
        /// <returns></returns>
        public static IEnumerable <RawCapture> GetSequence(ICaptureDevice dev, bool maskExceptions = true)
        {
            try
            {
                dev.Open();

                while (true)
                {
                    RawCapture packet = null;
                    try
                    {
                        packet = dev.GetNextPacket();
                    }
                    catch (PcapException pe)
                    {
                        if (!maskExceptions)
                        {
                            throw pe;
                        }
                    }

                    if (packet == null)
                    {
                        break;
                    }
                    yield return(packet);
                }
            }
            finally
            {
                dev.Close();
            }
        }
Beispiel #8
0
        /// <summary>
        /// This function opens an interface "Device" an starts looking
        /// for "jdnq" which are the ICMP-Like packets.
        /// </summary>
        public static void runn(ICaptureDevice device)
        {
            //Register our handler function to the 'packet arrival' event
            device.OnPacketArrival +=
                new PacketArrivalEventHandler(device_OnPacketArrival);

            //Open the device for capturing
            int readTimeoutMilliseconds = 1000;

            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            // tcpdump filter to capture only icmp-like packets
            // "icmp" is "jdnq"
            string filter = shift("jdnq", -1);

            device.Filter = filter;

            // Start capture packets
            device.Capture();

            // Close the pcap device
            // (Note: this line will never be called since
            //  we're capturing infinite number of packets
            device.Close();
        }
Beispiel #9
0
        // Open the file to parse
        // returns true if successful, false otherwise
        public bool openPcap(string capFile)
        {
            try {
                // Get an offline device
                device = new CaptureFileReaderDevice(capFile);

                // Open the device
                device.Open();
            }
            catch (Exception e) {
                Console.WriteLine("Caught exception when opening file" + e.ToString());
                Console.ReadKey();
                return(false);
            }

            // Register our handler function to the 'packet arrival' event
            device.OnPacketArrival +=
                new PacketArrivalEventHandler(device_OnPacketArrival);

            Console.WriteLine();
            Console.WriteLine("-- Capturing from '{0}', hit 'Ctrl-C' to exit...", capFile);

            // Start capture 'INFINTE' number of packets
            // This method will return when EOF reached.
            device.Capture();

            // Close the pcap device
            device.Close();
            Console.WriteLine("-- End of file reached.");
            Console.Write("Hit 'Enter' to exit...");
            Console.ReadLine();
            return(true);
        }
Beispiel #10
0
    /*
     * FUnkce pro veškeré zachytávání paketů
     * Otevře dané rozhraní pro naslouchání a poté načítá pakety a volá funkci na zpracování dokud
     * nedosáhne daného čísla
     */
    public void catch_packets(Argument arg)
    {
        //Otevře Device pro naslouchání s nastaveným timeoutem
        int timeout = 10000;
        int counter = 0;

        Device.Open(DeviceMode.Promiscuous, timeout);
        RawCapture packet;

        // Cyklus načítá pakety
        while ((packet = Device.GetNextPacket()) != null)
        {
            //Volá funkci na zpracování paketu a pokud vrátí true (např. pokud jde o TCP protokol když
            //je zvolena funkce na naslouchání tcp, zvýší counter
            if (work_packet(packet, arg))
            {
                counter++;
                if (counter != arg.Num)
                {
                    Console.WriteLine("");
                }
            }
            if (counter == arg.Num)
            {
                break;
            }
        }

        Device.Close();
    }
Beispiel #11
0
        private static void Cleanup(ICaptureDevice device)
        {
            try
            {
                // Try and wait for the thread
                Thread.Sleep(1000);
                device.StopCapture();
                Console.WriteLine("-- Capture stopped.");
                //Console.WriteLine(device.Statistics.ToString());
                device.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            var macList = new List <string>();

            foreach (var mac in SourceMac)
            {
                macList.Add(string.Join(":", mac.GetAddressBytes().Select(x => x.ToString("X2"))));
            }

            foreach (var mac in macList)
            {
                Console.WriteLine($"{mac}");
            }
        }
Beispiel #12
0
        private void drpDevices_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (selectedDevice != null && selectedDevice.Started)
            {
                selectedDevice.Close();
            }
            if (drpDevices.SelectedIndex == -1)
            {
                return;
            }
            var index = drpDevices.SelectedIndex;

            selectedDevice = CaptureDeviceList.Instance[index];
            selectedDevice.OnPacketArrival +=
                new PacketArrivalEventHandler(device_OnPacketArrival);
            int readTimeoutMilliseconds = 1000;

            selectedDevice.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            string filter = "ip and tcp";

            selectedDevice.Filter = filter;

            Task.Run(() =>
            {
                selectedDevice.Capture();
            });
        }
Beispiel #13
0
        private static void ServiceStart(bool starting)
        {
            try
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                string message;
                if (starting)
                {
                    message = $"Local service started at {DateTime.Now}";
                }
                else
                {
                    message = $"Local service has been shutdown at {DateTime.Now}";

                    for (int i = 0; i < Worker.devices.Count; i++)
                    {
                        ICaptureDevice device = Worker.devices[i];
                        device.StopCapture();
                        device.Close();
                    }
                }
                watch.Stop();
                watch.LogTime("Program", starting ? "StartAsync" : "StopAsync", message).Wait();
            }
            catch (Exception err)
            {
                err.LogErrors("Program", "ServiceStart").Wait();
            }
        }
Beispiel #14
0
        /*
         *  抓包函数
         */
        public void catchPacketFun()
        {
            //选择活动网卡
            ICaptureDevice device = getActiveNetAdapte();


            //将处理函数注册到"包到达"事件
            //我理解为当device网卡(上面选择的网卡)抓到包时,调用"处理函数",让"处理函数"处理包(显示/读取/修改等)
            device.OnPacketArrival +=
                new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);

            // Open the device for capturing
            //我理解为被抓包在1000ms时间内被读取的包,而不是只抓1000ms
            int readTimeoutMilliseconds = 1000;

            //打开网口,准备调用StartCapture()(阻塞函数/Capture(int packetCount)为非阻塞函数,使用方法再查询)开始抓包,抓到的包交由"处理函数"执行
            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            // 开始抓包
            device.StartCapture();
            log.writeLog("正在抓包...", log.msgType.info);

            //当colseNetAdapte参数被已经抓获pppoe账号的函数改写时停止抓包
            while (!colseNetAdapte)
            {
                Console.WriteLine("抓包循环...");
                Thread.Sleep(1000);
            }

            // 停止抓包
            device.StopCapture();
            // 关闭网口
            device.Close();
            log.writeLog("抓包终止...", log.msgType.info);
        }
Beispiel #15
0
        /// <summary>
        /// Stops the comm manager thread.
        /// </summary>
        public void Stop()
        {
            try
            {
                Trace.WriteLine("stopping communications manager");

                // kill loop
                runThread = false;
                Thread.Sleep(50);

                if (capDevice != null)
                {
                    if (capDevice.Started)
                    {
                        capDevice.StopCapture();
                    }
                    capDevice.Close();
                    capDevice = null;
                }

                // abort and join
                commMgrThread.Abort();
                commMgrThread.Join();
            }
            catch (Exception e)
            {
                Util.StackTrace(e, false);
            }
        }
Beispiel #16
0
        private void ShutdownInterface(ICaptureDevice device)
        {
            if (device == null)
            {
                throw new ArgumentException($"{nameof(device)} must not be null or empty");
            }
            else if (!device.Started)
            {
                return;
            }

            try
            {
                device.OnPacketArrival -= Device_OnPacketArrival;

                device.StopCapture();
                device.Close();

                if (_captureDevices.Contains(device))
                {
                    _captureDevices.Remove(device);
                }

                Trace.TraceInformation($"Stop listening on interface {device.Name}");
            }
            catch (Exception exception)
            {
                Trace.TraceError($"Can't gracefully stop listening on interface {device}", exception);
            }
        }
Beispiel #17
0
 private void StopCapture(ICaptureDevice pDevice)
 {
     if (_devices.Contains(pDevice))
         _devices.Remove(pDevice);
     pDevice.Close();
     pDevice.OnPacketArrival -= device_OnPacketArrival;
 }
Beispiel #18
0
 private void CloseCaptureDevice()
 {
     if (idev != null)
     {
         idev.Close();
     }
 }
Beispiel #19
0
 private void CaptureForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     Shutdown();
     _device.Close();
     _device.OnPacketArrival  -= device_OnPacketArrival;
     _device.OnCaptureStopped -= device_OnCaptureStopped;
     _device = null;
 }
Beispiel #20
0
 public void Execute(ICaptureDevice device)
 {
     device.OnPacketArrival += Device_OnPacketArrival;
     device.Open();
     device.Filter = "tcp port 4061";
     device.Capture();
     device.Close();
 }
Beispiel #21
0
        public void Disconnect()
        {
            _device.OnPacketArrival -= PacketHandler;
            _device.StopCapture();
            _device.Close();

            Disconnected?.Invoke();
        }
Beispiel #22
0
        public static void Send(CapDeviceToken t, byte[] packet)
        {
            ICaptureDevice dev = _mapping[t.ID];

            dev.Open();
            dev.SendPacket(packet);
            dev.Close();
        }
 public Task StopAsync(CancellationToken cancellationToken)
 {
     ConnectionManager.OnConnectionFound -= TcpConnectionManager_OnConnectionFound;
     CaptureDevice.OnPacketArrival       -= device_OnPacketArrival;
     CaptureDevice.StopCapture();
     CaptureDevice.Close();
     return(Task.CompletedTask);
 }
Beispiel #24
0
 private void Form1_FormClosed(object sender, FormClosedEventArgs e)
 {
     if (start)
     {
         device.StopCapture();
         device.Close();
     }
 }
Beispiel #25
0
 public ICaptureDevice Close()
 {
     if (device != null)
     {
         device.Close();
     }
     return(device);
 }
Beispiel #26
0
 public static void Execute(ICaptureDevice device, IOutputFormatter output)
 {
     device.OnPacketArrival += Device_OnPacketArrival;
     device.Open();
     device.Filter = "port 53";
     device.Capture();
     device.Close();
 }
        public static void stopListen()
        {
            // Stop the capturing process
            device.StopCapture();

            // Close the pcap device
            device.Close();
        }
        public void CapturePacket2(ICaptureDevice device, DeviceMode captureMode, int timeOutMillis)
        {
            // without events
            device.Open(captureMode, timeOutMillis);
            //     System19.Say("Im Gonna use device "+device.Name+" to Extract Packets ");
            Packet packet = null;

            device.Close();
        }
Beispiel #29
0
 private void StopCapture(ICaptureDevice pDevice)
 {
     if (_devices.Contains(pDevice))
     {
         _devices.Remove(pDevice);
     }
     pDevice.Close();
     pDevice.OnPacketArrival -= device_OnPacketArrival;
 }
Beispiel #30
0
        private void listen_Start()
        {
            ICaptureDevice device = devices[deviceIndex];

            device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);

            int readTimeoutMilliseconds = 1000;

            if (isPromisc == true)
            {
                device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            }
            else
            {
                device.Open(DeviceMode.Normal, readTimeoutMilliseconds);
            }

            string filter;

            if (decodeMode == false)
            {
                switch (typeOfDecode)
                {
                case 0:
                    break;

                case 1:
                    filter        = "ip and udp";
                    device.Filter = filter;
                    break;

                case 2:
                    filter        = "ip and tcp";
                    device.Filter = filter;
                    break;
                }
            }
            else
            {
                filter        = "udp port 161 or udp port 162";
                device.Filter = filter;
            }

            device.StartCapture();
            writeLine = "--- Listening For Packets ---";
            Invoke(new MethodInvoker(updateLog));
            while (!stopCapture)
            {
            }

            device.StopCapture();
            device.Close();

            writeLine = " -- Capture stopped, device closed. --";
            Invoke(new MethodInvoker(updateLog));
            stopCapture = false;
        }
Beispiel #31
0
 static void Main(string[] args)
 {
     {
         //Связываем объект файла с путем
         sw = new StreamWriter(path);
         // Получаем информацию о сетевых адаптерах компьютера
         CaptureDeviceList devices = CaptureDeviceList.Instance;
         // Если сетевых адаптеров нет, выводим ошибку и закрываем программу
         if (devices.Count < 1)
         {
             Console.WriteLine("No devices were found on this machine");
             Console.Write("Hit 'Enter' to exit...");
             Console.ReadLine();
             return;
         }
         Console.WriteLine("\nThe following devices are available:");
         Console.WriteLine("------------------------------------\n");
         // Выводим на экран список всех сетевых адаптеров
         for (int i = 0; i < devices.Count; i++)
         {
             Console.Write("{0}. ", i + 1);
             Console.WriteLine("{0}", devices[i].ToString());
         }
         //Предлагаем пользователю выбрать адаптер для захвата пакетов
         Console.WriteLine("Choose device number to capture packets:");
         int num = 0;
         //Пытаемся преобразовать выбор пользователя в число
         if ((!Int32.TryParse(Console.ReadLine(), out num)) || (num > devices.Count))
         {
             //Если пользователь ввел неправильные данные - выводим ошибку и закрываем программу
             Console.WriteLine("Incorrect device number");
             Console.Write("Hit 'Enter' to exit...");
             Console.ReadLine();
             return;
         }
         //Извлкаем выбранный адаптер из списка адаптеров
         ICaptureDevice device = devices[--num];
         //Регистрируем обработчик события "Приход пакета"
         device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
         //Открываем адаптер в "смешанном режиме" с интервалом захвата 1000 мс
         device.Open(DeviceMode.Promiscuous, 1000);
         Console.WriteLine("Listening on {0}, hit 'Enter' to stop...", device.Description);
         // Начинаем зазват пакетов
         device.StartCapture();
         // По нажатию 'Enter' захват останавливается
         Console.ReadLine();
         // Останавливаем захват пакетов
         device.StopCapture();
         // Закрываем адаптер
         device.Close();
         //Закрываем файл
         sw.Close();
         Console.Write("Hit 'Enter' to exit...");
         Console.ReadLine();
         return;
     }
 }
Beispiel #32
0
    public void UpdateDevInfo(ICaptureDevice dev)
    {
        // if we are sending packet to all adapters
        if (dev == null)
        {
            if (sIP == null)
            {
                sIP = IPAddress.Parse("255.255.255.255");
                Console.WriteLine("Set sIP to: " + sIP.ToString());
            }
            if (dIP == null)
            {
                dIP = IPAddress.Parse("255.255.255.255");
                Console.WriteLine("Set dIP to: " + dIP.ToString());
            }
            if (sMAC == null)
            {
                sMAC = PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF");
                Console.WriteLine("Set sMAC to: " + sMAC.ToString());
            }
            if (dMAC == null)
            {
                dMAC = PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF");
                Console.WriteLine("Set dMAC to: " + dMAC.ToString());
            }
        }
        // if we picked an actual adapter
        else
        {
            dev.Open();
            // if source address is not defined, fill out the sIP
            List<IPAddress> ipAddresses = Utility.GetIPAddress(dev);
            foreach (IPAddress add in ipAddresses)
            {
                if (sIP == null && dIP != null)
                {
                    if (dIP.ToString().Contains(".") && add.ToString().Contains("."))
                    {
                        sIP = add;
                        Console.WriteLine("Set sIP to: " + add.ToString());
                    }
                    else if (dIP.ToString().Contains(":") && add.ToString().Contains(":"))
                    {
                        sIP = add;
                        Console.WriteLine("Set sIP to: " + add.ToString());
                    }
                }
            }

            if (sIP == null)
            {
                Console.WriteLine("The chosen adapter did not have a valid address");
                Environment.Exit(1);
            }

            //fill out source mac if it is null
            if (sMAC == null)
            {
                sMAC = dev.MacAddress;
                Console.WriteLine("Set sMAC to: " + sMAC.ToString());
            }
            if (dMAC == null)
            {
                dMAC = PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF");
                Console.WriteLine("Set dMAC to: " + dMAC.ToString());
            }
            dev.Close();
        }
    }
Beispiel #33
0
        private int SendSynPacket(TcpPacket tcp)
        {
            tcp.SequenceNumber = 0;       //A TCP Sync Packet will always have a destination address of 0
            tcp.CWR = false;
            tcp.ECN = false;
            tcp.Urg = false;
            tcp.Ack = false;
            tcp.Psh = false;
            tcp.Rst = false;
            tcp.Syn = true;
            tcp.Fin = false;

            device = devices[1];

            device.Open(DeviceMode.Promiscuous, 20);

            device.SendPacket(tcp);

            device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            //device.StartCapture();

            RawCapture nexttcp = device.GetNextPacket();

            //device.StopCapture();

            if (nexttcp != null)
            {
                var packet = PacketDotNet.Packet.ParsePacket(nexttcp.LinkLayerType, nexttcp.Data);

                TcpPacket tcp1 = TcpPacket.GetEncapsulated(packet);

                if ((tcp1 != null) && (tcp1.Syn == true) && (tcp1.Ack == true))
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                return 0;
            }
            device.Close();
        }
        public static void Main(string[] Args)
        {
            int SpecifiedDevice = 0;
            try
            {
                foreach (string Argument in Args)
                {
                    if (Argument.StartsWith("d"))
                    {
                        SpecifiedDevice = Int32.Parse(Argument.Substring(2));
                    }
                    if (Argument.StartsWith("s"))
                    {
                        StatisticsInterval = Int32.Parse(Argument.Substring(2));
                    }
                    if (Argument.StartsWith("o"))
                    {
                        FileName = Argument.Substring(2);
                    }
                }
            }
            catch (Exception)
            {

            }

            // Print a welcome message
            Console.WriteLine("Welcome to Passive Network Discovery");

            LogFilePrompt:
            Console.WriteLine();
            Console.Write("Do you want use MySQL? [Y/n] ");
            ConsoleKeyInfo LogTypeKey = Console.ReadKey();
            Console.WriteLine();
            Console.WriteLine();

            if (LogTypeKey.KeyChar == 'n' || LogTypeKey.KeyChar == 'N')
            {
                // Use files
                LogType = FILE;
                // Print log filename note
                Console.WriteLine();
                Console.WriteLine("NOTE: This program will log to {0}", FileName);

            }
            else if (LogTypeKey.KeyChar == 'y' || LogTypeKey.KeyChar == 'Y' || LogTypeKey.Key == ConsoleKey.Enter)
            {
                // Use database
                LogType = DATABASE;
                Console.WriteLine("-- Connecting to MySQL server...");
                string DatabaseConnectionString = String.Format("server={0};port={1};user={2};password={3};database={4};",
                    DatabaseHost, DatabasePort, DatabaseUsername, DatabasePassword, DatabaseSchema);

                DatabaseConnection = new MySqlConnection(DatabaseConnectionString);
                SecondDatabaseConnection = new MySqlConnection(DatabaseConnectionString);
                try
                {
                    DatabaseConnection.Open();
                    SecondDatabaseConnection.Open();
                    Console.WriteLine("-- Connected to MySQL server successfully!");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("-- Error while connecting to MySQL server!");
                    Console.WriteLine(ex.ToString());
                    Console.Read();
                    return;
                }
            }
            else
            {
                // Please try again
                Console.WriteLine();
                Console.WriteLine("Did not understand that, please try again!");
                goto LogFilePrompt;
            }

            // Retrieve the device list
            var Devices = CaptureDeviceList.Instance;

            // If no devices were found print an error
            if (Devices.Count < 1)
            {
                Console.WriteLine("No devices were found on this machine");
                return;
            }

            if (SpecifiedDevice == 0)
            {
                Console.WriteLine();
                Console.WriteLine("The following devices are available on this machine:");
                Console.WriteLine("----------------------------------------------------");
                Console.WriteLine();

                int i = 1;

                // Print out the devices
                foreach (var TempDevice in Devices)
                {
                    // Description
                    Console.WriteLine("{0}) {1} {2}", i, TempDevice.Name, TempDevice.Description);
                    i++;
                }

                Console.WriteLine();
                Console.Write("-- Please choose a device to capture: ");
                SpecifiedDevice = int.Parse(Console.ReadLine());
            }

            try
            {
                Device = Devices[SpecifiedDevice - 1];
            }
            catch (Exception)
            {
                Console.WriteLine("This device doesn't exist");
                return;
            }

            // Register our handler function to the 'packet arrival' event
            Device.OnPacketArrival +=
                new PacketArrivalEventHandler(OnPacketArrival);

            // Open the device for capturing
            int ReadTimeoutMilliseconds = 1000;
            if (Device is AirPcapDevice)
            {
                // NOTE: AirPcap devices cannot disable local capture
                var AirPcap = Device as AirPcapDevice;
                AirPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp, ReadTimeoutMilliseconds);
            }
            else if (Device is WinPcapDevice)
            {
                var WinPcap = Device as WinPcapDevice;
                WinPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp | SharpPcap.WinPcap.OpenFlags.NoCaptureLocal, ReadTimeoutMilliseconds);
            }
            else if (Device is LibPcapLiveDevice)
            {
                var LivePcapDevice = Device as LibPcapLiveDevice;
                LivePcapDevice.Open(DeviceMode.Promiscuous, ReadTimeoutMilliseconds);
            }
            else
            {
                throw new System.InvalidOperationException("unknown device type of " + Device.GetType().ToString());
            }

            Console.WriteLine();
            Console.WriteLine("-- Listening on {0} {1}, hit 'Ctrl + C' to stop...",
                Device.Name, Device.Description);

            Console.CancelKeyPress += delegate
            {
                try
                {
                    // Stop the capturing process
                    Device.StopCapture();

                    Console.WriteLine();
                    Console.WriteLine("-- Capture stopped.");

                    // Close the pcap device
                    Device.Close();
                    DatabaseConnection.Close();
                }
                catch (Exception ex)
                {
                    // We do not care - at all!
                }
            };

            // Start the capturing process
            Device.StartCapture();

            Timer StatisticsTimer = new Timer();
            StatisticsTimer.Elapsed += new ElapsedEventHandler(DisplayStatisticsEvent);
            StatisticsTimer.Interval = StatisticsInterval;
            StatisticsTimer.Start();

            while (true) { Console.Read(); }
        }
        private void btnSendPacket_Click(object sender, RoutedEventArgs e)
        {
            device = gbxDevInfo.DataContext as ICaptureDevice;
            // Open the device
            device.Open();

            try
            {
                IPAddress ip = IPAddress.Parse(tbxSourceIp.Text);
                IPAddress ipaddress = System.Net.IPAddress.Parse(tbxDestinationIp.Text);
                TcpPacket tcpPakje = new TcpPacket(80, 80);
                IPv4Packet pakje = new IPv4Packet(ip, ipaddress);
                pakje.PayloadData = System.Text.Encoding.ASCII.GetBytes(tbxPayloadIp.Text);
                pakje.TimeToLive = int.Parse(tbxTTLIp.Text);
               // pakje.Protocol = tbxProtocolIp.Text;
                device.SendPacket(pakje);
                Console.WriteLine("-- Packet sent successfuly.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("-- " + ex.Message);
            }

            // Close the pcap device
            device.Close();
            Console.WriteLine("-- Device closed.");
        }
Beispiel #36
0
        /// <summary>
        /// IEnumerable helper allows for easy foreach usage, extension method and Linq usage
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<RawCapture> GetSequence(ICaptureDevice dev, bool maskExceptions = true)
        {
            try
            {
                dev.Open();

                while (true)
                {
                    RawCapture packet = null;
                    try
                    {
                        packet = dev.GetNextPacket();
                    }
                    catch (PcapException pe)
                    {
                        if (!maskExceptions)
                            throw pe;
                    }

                    if (packet == null)
                        break;
                    yield return packet;
                }
            }
            finally
            {
                dev.Close();
            }
        }
Beispiel #37
0
        /* Import a previous .pcap file */
        private void Import()
        {
            OpenFileDialog openfile = new OpenFileDialog();
            string path = "";
            openfile.ShowDialog();
            if (openfile.FileName != "")
                path = openfile.FileName;
            else
                return;

            try
            {
                device = new CaptureFileReaderDevice(path);
                device.Open();
            }
            catch (System.Exception)
            {
                MessageBox.Show("Cannot import the file!");
                return;
            }
            TotalPacket.Items.Clear();
            RawCaptureList.Clear();
            PacketCount = 0;
            device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device.Capture();
            device.Close();
        }