예제 #1
0
        //start
        private void start_Click(object sender, RoutedEventArgs e)
        {
            if (device == null || device.Started)
            {
                return;
            }
            try
            {
                device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
                int readTimeoutMillseconds = 1000;
                device.Open(DeviceMode.Normal, readTimeoutMillseconds);
                if (packetList.Items.Count > 0)
                {
                    // packetList.ItemsSource = null;
                    packets.Clear();
                }
                //packetList.Items.Clear();
                Console.WriteLine("statr capture");
            }
            catch (Exception ex)
            {
                //System.Windows.MessageBox.Show(ex.Message);
            }

            if (filterSelect == "tcp and udp")
            {
                try
                {
                    filter = "tcp and udp";
                    //device.Filter = filter;
                    device.StartCapture();
                    Console.WriteLine("start capture");
                }
                catch (Exception ex)
                {
                    //System.Windows.MessageBox.Show(ex.Message);
                }
            }
            if (filterSelect == "Tcp")
            {
                filter        = "tcp";
                device.Filter = filter;
                device.StartCapture();
            }
            if (filterSelect == "UDP")
            {
                filter        = "udp";
                device.Filter = filter;
                device.StartCapture();
            }
            else if (filterSelect == "HTTP")
            {
                filter        = "tcp and port 80";
                device.Filter = filter;
                device.StartCapture();
            }
        }
예제 #2
0
        /// <summary>
        /// Starts the target manager thread.
        /// </summary>
        public void Start()
        {
            Messages.Trace("starting communications manager");

            // get the packet capture device
            CaptureDeviceList devices = CaptureDeviceList.Instance;

            capDevice = devices[Program.interfaceToUse];
            Messages.Trace("using [" + capDevice.Description + "] for network capture");

            capDevice.OnPacketArrival += capDevice_OnPacketArrival;

            if (capDevice is WinPcapDevice)
            {
                WinPcapDevice winPcap = capDevice as WinPcapDevice;
                winPcap.Open(OpenFlags.Promiscuous | OpenFlags.NoCaptureLocal | OpenFlags.MaxResponsiveness, readTimeoutMilliseconds);
            }
            else if (capDevice is LibPcapLiveDevice)
            {
                LibPcapLiveDevice livePcapDevice = capDevice as LibPcapLiveDevice;
                livePcapDevice.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            }
            else
            {
                throw new InvalidOperationException("unknown device type of " + capDevice.GetType().ToString());
            }

            capDevice.StartCapture();

            // start loop
            runThread = true;
            commMgrThread.Start();
        }
예제 #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)
            {
            }
        }
예제 #4
0
        public bool OpenDevice(ICaptureDevice device)
        {
            mainForm.WriteLine(string.Format("Using device {0}", Device.Description), Color.Black);
            mainForm.WriteLine("");
            int readTimeoutMilliseconds = 1000;

            if (device is SharpPcap.AirPcap.AirPcapDevice)
            {
                // NOTE: AirPcap devices cannot disable local capture
                var airPcap = device as SharpPcap.AirPcap.AirPcapDevice;
                airPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp, readTimeoutMilliseconds);
            }
            else if (device is SharpPcap.WinPcap.WinPcapDevice)
            {
                var winPcap = device as SharpPcap.WinPcap.WinPcapDevice;
                winPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp | SharpPcap.WinPcap.OpenFlags.NoCaptureLocal, readTimeoutMilliseconds);
            }
            else if (device is SharpPcap.LibPcap.LibPcapLiveDevice)
            {
                var livePcapDevice = device as SharpPcap.LibPcap.LibPcapLiveDevice;
                livePcapDevice.Open(SharpPcap.DeviceMode.Promiscuous, readTimeoutMilliseconds);
            }
            else
            {
                mainForm.WriteLine("Unknown device type of " + device.GetType().ToString(), Color.Red);
                return(false);
            }
            // Register our handler function to the 'packet arrival' event
            device.OnPacketArrival +=
                new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            device.StartCapture();
            return(true);
        }
예제 #5
0
 PacketHandler(WinPcapDeviceList devices, ListView listView)
 {
     if (devices.Equals(null))
     {
         Dialog fatalErr = Dialog.Instance;
         fatalErr.showMsgBox("Fatal Error!", "Fatal Error Occured!\nPlease restart this program!");
     }
     else
     {
         if (listView.SelectedItem == null)
         {
             Dialog noChoiceErr = Dialog.Instance;
             noChoiceErr.showMsgBox("Error!", "Please choose the lancard you are using first!");
         }
         else
         {
             hwnd = (new GetWindow()).FindWindow(TARGET_PROCESS_WINDOW_TITLE);
             Mouse.SetForegroundWindow(hwnd);
             device = devices[listView.SelectedIndex];
             device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
             device.Open(DeviceMode.Promiscuous, 2000);
             device.Filter = "ip and tcp";
             device.StartCapture();
             clickSimulate(MousePositionData.FIRST);
         }
     }
 }
예제 #6
0
        private void StartCapture(int itemIndex)
        {
            packetCount             = 0;
            device                  = CaptureDeviceList.Instance[itemIndex];
            packetStrings           = new Queue <PacketWrapper>();
            bs                      = new BindingSource();
            dataGridView.DataSource = bs;
            LastStatisticsOutput    = DateTime.Now;

            // start the background thread
            BackgroundThreadStop = false;
            backgroundThread     = new System.Threading.Thread(BackgroundThread);
            backgroundThread.Start();

            // setup background capture
            arrivalEventHandler        = new PacketArrivalEventHandler(device_OnPacketArrival);
            device.OnPacketArrival    += arrivalEventHandler;
            captureStoppedEventHandler = new CaptureStoppedEventHandler(device_OnCaptureStopped);
            device.OnCaptureStopped   += captureStoppedEventHandler;
            device.Open();

            // force an initial statistics update
            captureStatistics = device.Statistics;
            UpdateCaptureStatistics();

            // start the background capture
            device.StartCapture();

            // disable the stop icon since the capture has stopped
            startStopToolStripButton.Image       = global::WinformsExample.Properties.Resources.stop_icon_enabled;
            startStopToolStripButton.ToolTipText = "Stop capture";
        }
예제 #7
0
        public void StartCapture(int itemIndex, string filter)
        {
            packetCount          = 0;
            device               = CaptureDeviceList.Instance[itemIndex]; //选折网卡
            packetStrings        = new Queue <PacketWrapper>();
            LastStatisticsOutput = DateTime.Now;

            // start the background thread
            BackgroundThreadStop          = false;
            backgroundThread              = new Thread(BackgroundThread);
            backgroundThread.IsBackground = true;
            backgroundThread.Start();

            // setup background capture
            arrivalEventHandler        = new PacketArrivalEventHandler(device_OnPacketArrival);   //当包抵达时要进行的操作
            device.OnPacketArrival    += arrivalEventHandler;
            captureStoppedEventHandler = new CaptureStoppedEventHandler(device_OnCaptureStopped); //停止抓包要做的操作
            device.OnCaptureStopped   += captureStoppedEventHandler;
            device.Open();

            device.Filter = filter;

            Debug.WriteLine("-- 正在监听网卡{0} {1},开始抓包!", device.Name, device.Description);
            // start the background capture
            device.StartCapture();
        }
예제 #8
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();
            }
        }
예제 #9
0
        private void StartBtn_Click(object sender, EventArgs e)
        {
            if (startBtn.Text == "Start")
            {
                try
                {
                    maxPackets = Convert.ToInt32(numPacketsTxtBox.Text);
                }
                catch (System.FormatException)
                {
                    MessageBox.Show("The number of packets must be a number you silly billy");
                    numPacketsTxtBox.Clear();
                    return;
                }

                Debug.Write("Max Packets: " + maxPackets);

                progressLabel.Visible = true;
                progressTxt.Visible   = true;
                progressTxt.Text      = "0/" + maxPackets;

                timer1.Enabled = true;
                string filter = "ip and tcp";
                device.Filter = filter;
                device.StartCapture();
                startBtn.Text = "Stop";
            }

            else
            {
                device.StopCapture();
                startBtn.Text  = "Start";
                timer1.Enabled = false;
            }
        }
예제 #10
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;
     }
 }
예제 #11
0
        public void Connect(string deviceName)
        {
            var detector = new PortDetector();
            var ports    = detector.GetUdpPorts("Albion-Online");

            foreach (var port in ports)
            {
                _udpPorts.Add(port);
            }

            var builder = ReceiverBuilder.Create();

            IncomeLowEventsSource  = new IncomeLowEventsSource(builder);
            OutcomeLowEventsSource = new OutcomeLowEventsSource(builder);

            _receiver = builder.Build();

            _device = CaptureDeviceList.Instance.Single(d => d.Name == deviceName);
            _device.Open(DeviceMode.Promiscuous, (int)TimeSpan.FromSeconds(1).TotalMilliseconds);

            foreach (var udpPort in _udpPorts)
            {
                IPortListener portListener = new PortListener(_device, udpPort, ChannelProtocol.UDP);
                _udps.Add(portListener);
                portListener.DataCaptured += Udp_OnData;
                portListener.Connect();
            }

            _device.StartCapture();

            EventsSource = new EventsSource(IncomeLowEventsSource, BuffRepository, Avatar);
            Connected?.Invoke();
        }
예제 #12
0
        /// <summary>
        /// Start capturing packets on the given device.
        /// </summary>
        /// <param name="device">The device on which to start capturing packets.</param>
        private void StartCaptureOnDevice(ICaptureDevice device)
        {
            // The following code is taken and modified from SharpPcap's Github repository's
            // example 'BasicCap'
            // https://github.com/chmorgan/sharppcap/blob/master/Examples/Example3.BasicCap/Program.cs

            device.OnPacketArrival += HandlePacketArrival;

            // Open the device for capturing
            if (device is NpcapDevice)
            {
                var nPcap = device as NpcapDevice;
                // nPcap.Open(OpenFlags.DataTransferUdp | OpenFlags.NoCaptureLocal, _readTimeout);
                nPcap.Open(OpenFlags.Promiscuous, _readTimeout);
            }
            else if (device is LibPcapLiveDevice)
            {
                var livePcapDevice = device as LibPcapLiveDevice;
                livePcapDevice.Open(DeviceMode.Promiscuous, _readTimeout, MonitorMode.Active);
            }
            else
            {
                throw new InvalidOperationException($"Unknown device type of {device.GetType()}");
            }

            // Start the capturing proccess
            device.StartCapture();
        }
예제 #13
0
        internal void Start()
        {
            _device.OnPacketArrival += new PacketArrivalEventHandler(device_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(OpenFlags.DataTransferUdp, readTimeoutMilliseconds);
            //}
            //else
            if (_device is WinPcapDevice)
            {
                var winPcap = _device as WinPcapDevice;
                winPcap.Open(OpenFlags.DataTransferUdp | 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());
            }

            _tcpConnectionManager.OnConnectionFound += OnConnectionFound;

            _device.StartCapture();
        }
예제 #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);
        }
예제 #15
0
        public void SetDevice(string name)
        {
            if (CurrentCaptureDevice == null || CurrentCaptureDevice.Name != name)
            {
                if (CurrentCaptureDevice != null)
                {
                    CurrentCaptureDevice.OnPacketArrival -= device_OnPacketArrival;
                    CurrentCaptureDevice.StopCapture();
                }

                CurrentCaptureDevice = CaptureDeviceList.Instance.First(i => i.Name == name);
                CurrentCaptureDevice.OnPacketArrival += device_OnPacketArrival;

                int readTimeoutMilliseconds = 1000;
                if (CurrentCaptureDevice is NpcapDevice)
                {
                    var nPcap = CurrentCaptureDevice as NpcapDevice;
                    nPcap.Open(SharpPcap.Npcap.OpenFlags.DataTransferUdp | SharpPcap.Npcap.OpenFlags.NoCaptureLocal, readTimeoutMilliseconds);
                }
                else if (CurrentCaptureDevice is LibPcapLiveDevice)
                {
                    var livePcapDevice = CurrentCaptureDevice as LibPcapLiveDevice;
                    livePcapDevice.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
                }
                else
                {
                    throw new InvalidOperationException("unknown device type of " + CurrentCaptureDevice.GetType().ToString());
                }

                CurrentCaptureDevice.StartCapture();
            }
        }
예제 #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            // метод для получения списка устройств
            deviceList = CaptureDeviceList.Instance;

            int i = 0;

            foreach (var item in deviceList)
            {
                ICaptureDevice captureDevice = deviceList[i];
                captureDevice.OnPacketArrival += new PacketArrivalEventHandler(Program_OnPacketArrival);
                captureDevice.Open(DeviceMode.Promiscuous, 1000);

                captureDevice.StartCapture();

                Thread.Sleep(1000);
                captureDevice.OnPacketArrival -= new PacketArrivalEventHandler(Program_OnPacketArrival);

                if (ip != "")
                {
                    listBox1.Items.Add("№" + i + " - " + ip);
                }
                i++;
            }
        }
예제 #17
0
 // старт
 private void button1_Click(object sender, EventArgs e)
 {
     if (!start)
     {
         button1.Text     = "Stop";
         button12.Visible = false;
         button1.FlatAppearance.BorderColor = Color.Red;
         catched = 0;
         start   = true;
         // выбор устройств для прослушки
         device = list[comboBox1.SelectedIndex];
         // событие, происходящее при поимке пакета
         device.OnPacketArrival += new PacketArrivalEventHandler(capture_event);
         // установление Promiscuous mode
         device.Open(DeviceMode.Promiscuous);
         // захват
         device.StartCapture();
     }
     else
     {
         button1.Text     = "Start";
         button12.Visible = true;
         button1.FlatAppearance.BorderColor = Color.DimGray;
         device.StopCapture();
         start = false;
     }
 }
예제 #18
0
        public void Start(string captureFileName = null)
        {
            _device.OnPacketArrival += DeviceOnPacketArrival;
            if (!string.IsNullOrEmpty(captureFileName))
            {
                var captureWriter = new CaptureFileWriterDevice(captureFileName);
                _device.OnPacketArrival += (sender, args) => captureWriter.Write(args.Packet);
            }

            if (_mode == Mode.File)
            {
                _device.Open();
            }
            else if (_device is NpcapDevice nPCap)
            {
                nPCap.Open(OpenFlags.DataTransferUdp | OpenFlags.NoCaptureLocal | OpenFlags.MaxResponsiveness, 1000);
            }
            else
            {
                _device.Open(DeviceMode.Promiscuous, 1000);
            }

            _device.Filter = Filter;
            _device.StartCapture();
        }
예제 #19
0
        /// <summary>
        /// 启动网卡
        /// </summary>
        private void Start()
        {
            if (device == null || device.Started)
            {
                return;
            }

            bufferList = new List <RawCapture>();
            Clear();//清理原有的数据
            isStartAnalyzer = true;


            StartAnalyzer();//启动分析线程


            try
            {
                device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
                device.Open(devMode, readTimeOut);
                device.StartCapture();

                UIConfig(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

                UIConfig(false);
            }
            InitChart();
        }
예제 #20
0
 private void StartDevice(ICaptureDevice device)
 {
     if (!device.Started)
     {
         device.OnPacketArrival += I_OnPacketArrival;
         device.Open(DeviceMode.Normal);
         device.StartCapture();
     }
     else
     {
         StopDevice(device);
         device.OnPacketArrival += I_OnPacketArrival;
         device.Open(DeviceMode.Normal);
         device.StartCapture();
     }
 }
예제 #21
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            device = CaptureDeviceList.Instance[cmbDeviceList.SelectedIndex];
            device.Open();
            device.Filter = "tcp and (port " + config.LoginAgentPort + " or port " + config.ZoneAgentPort + ") and host " + config.ServerIp;
            packetStrings = new Queue <A3Packet>();
            packetData    = new List <A3Packet>();

            bs = new BindingSource();
            dataGridPackets.DataSource = bs;

            BackgroundThreadStop = false;
            backgroundThread     = new Thread(BackgroundThread);
            backgroundThread.Start();

            arrivalEventHandler        = new PacketArrivalEventHandler(device_OnPacketArrival);
            device.OnPacketArrival    += arrivalEventHandler;
            captureStoppedEventHandler = new CaptureStoppedEventHandler(device_OnCaptureStopped);
            device.OnCaptureStopped   += captureStoppedEventHandler;

            device.Open();

            // start the background capture
            device.StartCapture();

            btnStart.Enabled = false;
            btnStop.Enabled  = true;
            lblStatus.Text   = "Capturing packets started ...";
            this.Text        = this.Text + "*";
        }
예제 #22
0
 //开始捕获方法
 private void Start_Capture(ICaptureDevice dev)
 {
     this.State           = true;                                       //设置运行状态
     dev.OnPacketArrival += new PacketArrivalEventHandler(Fun_Arrival); //注册处理包事件
     dev.Open(mode);                                                    //开启
     dev.StartCapture();                                                //开始捕获(异步)
 }
예제 #23
0
        private void StartCapture(int itemIndex)
        {
            packetCount          = 0;
            device               = CaptureDeviceList.Instance[itemIndex];
            packetStrings        = new Queue <PacketWrapper>();
            bs                   = new BindingSource();
            dgvData.DataSource   = bs;
            LastStatisticsOutput = DateTime.Now;

            // start the background thread
            backgroundThreadStop = false;
            backgroundThread     = new Thread(BackgroundThread);
            backgroundThread.Start();


            // setup background capture
            device.OnPacketArrival  += new PacketArrivalEventHandler(device_OnPacketArrival);
            device.OnCaptureStopped += new CaptureStoppedEventHandler(device_OnCaptureStopped);
            device.Open();

            // tcpdump filter to capture only TCP/IP packets
            string filter = "ip and tcp or udp";

            device.Filter = filter;

            // force an initial statistics update
            captureStatistics = device.Statistics;
            UpdateCaptureStatistics();

            // start the background capture
            device.StartCapture();

            btnStop.Enabled = true;
        }
예제 #24
0
        private void Start()
        {
            ICaptureDevice device = PacketDeviceSelector.AskForPacketDevice();

            device.OnPacketArrival += new PacketArrivalEventHandler(PacketHandler);
            device.Open(DeviceMode.Promiscuous, 1000);
            device.StartCapture();
        }
예제 #25
0
        public static void listen()
        {
            // Print SharpPcap version
            string ver = SharpPcap.Version.VersionString;

            Console.WriteLine("SharpPcap {0}, Example1.IfList.cs", ver);

            // Retrieve the device list
            CaptureDeviceList 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;
            }

            Console.WriteLine("\nThe following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------\n");

            // Print out the available network devices
            foreach (ICaptureDevice dev in devices)
            {
                Console.WriteLine("{0}\n", dev.ToString());
            }

            //Console.Write("Hit 'Enter' to exit...");
            //Console.ReadLine();

            // Extract a device from the list
            device = devices[3];

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

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

            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            //string filter = "ip and tcp";
            string filter = "ip";

            device.Filter = filter;


            Console.WriteLine("-- Listening on {0}, hit 'Enter' to stop...",
                              device.Description);

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


            // Wait for 'Enter' from the user.
            Console.ReadLine();
        }
예제 #26
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;
        }
예제 #27
0
 public void OpenNcapturePackets(ICaptureDevice device, DeviceMode captureMode, int timeOutMillis)
 {
     device.OnPacketArrival += new PacketArrivalEventHandler(Device_OnPacketArrival);
     // open the device for capturing
     device.Open(captureMode, timeOutMillis); // read all packets on network # if normal read Current Pcs Packets only
     System19.Say("I am Going to use device {0} to Extract Packets ", device.Description);
     device.StartCapture();                   // starts capturing packets
     //device.StopCapture();
 }
예제 #28
0
 private void Start()
 {
     _authPort = Convert.ToUInt16(AuthPortTxt.Text);
     _gamePort = Convert.ToUInt16(GamePortTxt.Text);
     _currentDevice.Open();
     _currentDevice.Filter           = string.Format("(dst host {0} || src host {0}) && ip proto \\tcp", ServerIPTxt.Text);
     _currentDevice.OnPacketArrival += CurrentDevice_OnPacketArrival;
     _currentDevice.StartCapture();
 }
예제 #29
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;
     }
 }
예제 #30
0
        public void StartSniffing(CancellationToken ct)
        {
            ClearOldSniffingsData();
            ICaptureDevice selectedDevice = GetSelectedDevice();

            if (selectedDevice is NpcapDevice)
            {
                var nPcap = selectedDevice as SharpPcap.Npcap.NpcapDevice;
                if (PromisciousMode)
                {
                    nPcap.Open(SharpPcap.Npcap.OpenFlags.Promiscuous, ReadTimeoutMilliseconds);
                }
                else
                {
                    nPcap.Open();
                }

                nPcap.Mode = CaptureMode.Packets;
            }
            else if (selectedDevice is SharpPcap.LibPcap.LibPcapLiveDevice)
            {
                var livePcapDevice = selectedDevice as SharpPcap.LibPcap.LibPcapLiveDevice;
                livePcapDevice.Open(PromisciousMode ? DeviceMode.Promiscuous : DeviceMode.Normal);
            }
            else
            {
                throw new InvalidOperationException("Unknown device type of " + SelectedDeviceName.GetType().ToString());
            }

            // Setup capture filter.
            SetupBpfFilter(selectedDevice);

            // Register our handler function to the 'packet arrival' event.
            selectedDevice.OnPacketArrival += InsertPacketToQueue;

            // Start the packet procesing thread.
            StartPacketProcessingThread();

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

            // Wait for sniffing to be stoped by user.
            WaitForStopSniffingSignal(ct);

            // Stop the capturing process.
            selectedDevice.StopCapture();

            // Waiting on the packet procesing thread to finish.
            StopPacketProcessingThread();

            // Close the pcap device
            selectedDevice.Close();

            // Raise events for unfinished sessions.
            HandleUnfinishedSessions();
        }
예제 #31
0
        public void listingPackets(ICaptureDevice dev)
        {
            device = dev;
            int readTimeoutMilliseconds = 1000;

            backgroundThread = new Thread(BackgroundThread);
            backgroundThread.Start();

            device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            device.StartCapture();
        }
예제 #32
0
        public void sniff()
        {
            r_id = 1;
            // Print SharpPcap version
            string ver = SharpPcap.Version.VersionString;
            Console.WriteLine("SharpPcap {0}, Example1.IfList.cs", ver);

            // Retrieve the device list
            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;
            }

            Console.WriteLine("\nThe following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------\n");

            // Print out the available network devices
            foreach (ICaptureDevice dev in devices)
                Console.WriteLine("{0}\n", dev.ToString());

            Console.Write("Hit 'Enter' to exit...");
            // Console.ReadLine();
            // Extract a device from the list
            device = devices[0];

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

            // Open the device for capturing
            int readTimeoutMilliseconds = 1000;
            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            Console.WriteLine("-- Listening on {0}, hit 'Enter' to stop...", device.Description);

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

            // Wait for 'Enter' from the user.
            //while (true) { };
        }
예제 #33
0
        public void Start()
        {
            var deviceList = CaptureDeviceList.Instance;// захват всех сетевых устройств

            GlobalDeviceClient = deviceList[0];
            GlobalDeviceServer = deviceList[1];

            proc.Start();// старт потока по обработке пакетов

            //// MAC1 -> MAC2
            GlobalDeviceClient.OnPacketArrival += new PacketArrivalEventHandler(Program_OnPacketArrival10);
            GlobalDeviceClient.Open();
            GlobalDeviceClient.StartCapture();

            //// MAC2 -> MAC1
            GlobalDeviceServer.OnPacketArrival += new PacketArrivalEventHandler(Program_OnPacketArrival10);
            GlobalDeviceServer.Open();
            GlobalDeviceServer.StartCapture();
        }
예제 #34
0
        private void StartCapture(int itemIndex)
        {
            device = CaptureDeviceList.Instance[itemIndex];

            // start the background thread
            BackgroundThreadStop = false;
            backgroundThread = new System.Threading.Thread(BackgroundThread);
            backgroundThread.Start();

            // setup background capture
            arrivalEventHandler = new PacketArrivalEventHandler(device_OnPacketArrival);
            device.OnPacketArrival += arrivalEventHandler;
            device.Open();
            if (filter!=null)
            device.Filter = filter;
            // start the background capture
            device.StartCapture();
            timer1.Start();
        }
예제 #35
0
        private void button1_Click(object sender, EventArgs e)
        {
            deviceMasterSent.StopCapture();
            deviceMasterSent.Close();
            deviceMasterRecv.StopCapture();
            deviceMasterRecv.Close();
            device1Sent.StopCapture();
            device1Sent.Close();
            device2Sent.StopCapture();
            device2Sent.Close();
            device3Sent.StopCapture();
            device3Sent.Close();

            //isDeviceOpen = false;

            deviceMasterSent = devices[deviceNumber];
            deviceMasterRecv = devices[deviceNumber];
            device1Sent = devices[deviceNumber];
            device1Recv = devices[deviceNumber];
            device2Sent = devices[deviceNumber];
            device2Recv = devices[deviceNumber];
            device3Sent = devices[deviceNumber];
            device3Recv = devices[deviceNumber];

            Console.WriteLine("-- Listening on {0}", deviceMasterSent.Description);

            // Register our handler function to the
            // 'packet arrival' event
            deviceMasterSent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            deviceMasterRecv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device1Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device1Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device2Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device2Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device3Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device3Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);

            // Open the device for capturing
            deviceMasterSent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            deviceMasterRecv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device1Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device1Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device2Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device2Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device3Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device3Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            /*// Set device to statistics mode
            deviceMasterSent.Mode = CaptureMode.Statistics;
            deviceMasterRecv.Mode = CaptureMode.Statistics;
            device1Sent.Mode = CaptureMode.Statistics;
            device1Recv.Mode = CaptureMode.Statistics;
            device2Sent.Mode = CaptureMode.Statistics;
            device2Recv.Mode = CaptureMode.Statistics;
            device3Sent.Mode = CaptureMode.Statistics;
            device3Recv.Mode = CaptureMode.Statistics;*/

            // Set device filter policy
            //deviceMasterSent.Filter = "src net 161.246.73.99";
            //deviceMasterRecv.Filter = "dst net 161.246.73.99";
            device1Sent.Filter = "src net 192.168.137.21";
            device1Recv.Filter = "dst net 192.168.137.21";
            device2Sent.Filter = "src net 192.168.137.22";
            device2Recv.Filter = "dst net 192.168.137.22";
            device3Sent.Filter = "src net 192.168.137.23";
            device3Recv.Filter = "dst net 192.168.137.23";

            deviceMasterSent.StartCapture();
            deviceMasterRecv.StartCapture();
            device1Sent.StartCapture();
            device1Recv.StartCapture();
            device2Sent.StartCapture();
            device2Recv.StartCapture();
            device3Sent.StartCapture();

            //isDeviceOpen = true;
        }
예제 #36
0
        /*private static void device_OnPcapStatistics(object sender, SharpPcap.WinPcap.StatisticsModeEventArgs e)
        {
            Console.WriteLine("bytes : {0}", e.Statistics.RecievedBytes);
            /*if (sender.Equals(rtChartPlotter.Form1.deviceMasterSent))
                devicesPacketLengthS[0] += e.Statistics.RecievedBytes;
            else if (sender.Equals(deviceMasterRecv))
                devicesPacketLengthR[0] += e.Statistics.RecievedBytes;

            if (sender.Equals(device1Sent))
                devicesPacketLengthS[1] += e.Statistics.RecievedBytes;
            else if (sender.Equals(device1Recv))
                devicesPacketLengthR[1] += e.Statistics.RecievedBytes;

            else if (sender.Equals(device2Sent))
                devicesPacketLengthS[2] += e.Statistics.RecievedBytes;
            else if (sender.Equals(device2Recv))
                devicesPacketLengthR[2] += e.Statistics.RecievedBytes;

            else if (sender.Equals(device3Sent))
                devicesPacketLengthS[3] += e.Statistics.RecievedBytes;
            else if (sender.Equals(device3Recv))
                devicesPacketLengthR[3] += e.Statistics.RecievedBytes;
        }*/
        private void Form1_Load(object sender, EventArgs e)
        {
            lines = File.ReadAllLines(@"c:\dinjter.csv").Select(a => a.Split(','));
            csv = from line in lines select (from piece in line select piece.Split(',')).ToArray();

            textboxStream = new TextBoxStreamWriter(textBox1);
            Console.SetOut(textboxStream);

            // Volt meter stub.
            textBox10.Text = "0.00 V";

            // Retrieve the device list
            devices = CaptureDeviceList.New();

            // If no devices were found print an error
            if (devices.Count < 1)
            {
                Console.WriteLine("No devices were found on this machine");
                return;
            }
            //set limit on NumericUpDown box
            this.numericUpDown1.Maximum = devices.Count-1;

            Console.WriteLine("The following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------");

            // Print out the available network devices
            foreach (ICaptureDevice dev in devices)
                Console.WriteLine("{0}\n", dev.ToString());

            device = devices[2];
            device.OnPacketArrival +=
            new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device.StartCapture();
            Console.WriteLine("device started");
            // Assign selected device to each members

            deviceMasterSent = devices[deviceNumber];
            device1Sent = devices[deviceNumber];
            device2Sent = devices[deviceNumber];
            device3Sent = devices[deviceNumber];
            deviceMasterRecv = devices[deviceNumber];
            device1Recv = devices[deviceNumber];
            device2Recv = devices[deviceNumber];
            device3Recv = devices[deviceNumber];

            // Register our handler function to the
            // 'packet statistics' event
            deviceMasterSent.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            deviceMasterRecv.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            device1Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device1Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device2Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device2Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device3Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
            device3Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);

            // Open the device for capturing
            deviceMasterSent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            deviceMasterRecv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device1Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device1Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device2Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device2Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device3Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device3Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            // Set device filter policy
            //deviceMasterSent.Filter = "src net 161.246.73.99";
            //deviceMasterRecv.Filter = "dst net 161.246.73.99";
            device1Sent.Filter = "src net 192.168.137.21";
            device1Recv.Filter = "dst net 192.168.137.21";
            device2Sent.Filter = "src net 192.168.137.22";
            device2Recv.Filter = "dst net 192.168.137.22";
            device3Sent.Filter = "src net 192.168.137.23";
            device3Recv.Filter = "dst net 192.168.137.23";

            Console.WriteLine("-- Listening on {0}, [Initial listening device]",
                deviceMasterSent.Description);

            // Start the capturing process
            deviceMasterSent.StartCapture();
            deviceMasterRecv.StartCapture();
            device1Sent.StartCapture();
            device1Recv.StartCapture();
            device2Sent.StartCapture();
            device2Recv.StartCapture();
            device3Sent.StartCapture();
            device3Recv.StartCapture();

            //isDeviceOpen = true;
        }
예제 #37
0
 /// <summary>
 /// Capturedevice the packet form specific 
 /// </summary>
 /// <param name="timeout"></param>
 /// <param name="device"></param>
 public void Start(int timeout, ICaptureDevice device)
 {
     device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(OnPacketArrival);
     device.Open(DeviceMode.Promiscuous, timeout);
     device.StartCapture();
 }
        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(); }
        }
예제 #39
0
        private void Form1_Load(object sender, EventArgs e)
        {
            timeDelay = timer1.Interval;

            lines = File.ReadAllLines(@"c:\dinjter.csv").Select(a => a.Split(','));
            csv = from line in lines select (from piece in line select piece.Split(',')).ToArray();

            textboxStream = new TextBoxStreamWriter(textBox1);
            Console.SetOut(textboxStream);

            // Volt meter stub.
            textBox10.Text = "0.00 V";

            // Retrieve the device list
            devices = CaptureDeviceList.New();

            // If no devices were found print an error
            if (devices.Count < 1)
            {
                Console.WriteLine("No devices were found on this machine");
                return;
            }
            //set limit on NumericUpDown box
            this.numericUpDown1.Maximum = devices.Count - 1;

            Console.WriteLine("The following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------");

            // Print out the available network devices
            foreach (ICaptureDevice dev in devices)
                Console.WriteLine("{0}\n", dev.ToString());

            device0s = devices[0];
            device0r = devices[0];
            device1s = devices[0];
            device1r = devices[0];
            device2s = devices[0];
            device2r = devices[0];
            device3s = devices[0];
            device3r = devices[0];

            device0s.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            device1s.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            device1r.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            device2s.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            device2r.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            device3s.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            device3r.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);

            device0s.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device1s.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device1r.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device2s.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device2r.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device3s.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            device3r.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            device0s.StartCapture();
            //device1s.StartCapture();
            //device1r.StartCapture();
            //device2s.StartCapture();
            //device2r.StartCapture();
            //device3s.StartCapture();
            //device3r.StartCapture();

            Console.WriteLine("device started");
        }
예제 #40
0
        private void button1_Click(object sender, EventArgs e)
        {
            device0s.StopCapture();
            device0s.Close();

            //isDeviceOpen = false;

            device0s = devices[deviceNumber];
            device0s = devices[deviceNumber];

            Console.WriteLine("-- Listening on {0}", device0s.Description);

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

            // Open the device for capturing
            device0s.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            device0s.StartCapture();

            //isDeviceOpen = true;
        }
예제 #41
0
        private void btnStartCapture_Click(object sender, RoutedEventArgs e)
        {
            // Extract a device from the list
            device = gbxDevInfo.DataContext as ICaptureDevice;

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

            // Open the device for capturing
            int readTimeoutMilliseconds = 1000;
            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            Console.WriteLine("-- Listening on {0}, hit 'Enter' to stop...",
                device.Description);

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

            // Wait for 'Enter' from the user.
            Console.ReadLine();
        }
예제 #42
0
        public void StartCapture(string deviceName, string ip)
        {
            if (deviceName == "" || ip == "")
            {
                throw new Exception("Device Input Fail");
            }

            //Get our index back. (0) blabla
            int index = Convert.ToInt32(deviceName.Split(')')[0].Replace("(", ""));

            if (WinPcapDeviceList.Instance.Count <= index)
            {
                throw new Exception("Device Fail");
            }

            device = WinPcapDeviceList.Instance[index];

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

            // Open the device for capturing
            int readTimeoutMilliseconds = 1000;
            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            //Filter
            string filter = "host " + ip;
            device.Filter = filter;
            captureIp = ip;

            // Start the capturing process
            device.StartCapture();
        }
예제 #43
0
        private bool _StartCapture()
        {
            // if capturing is already started, just return true
            if (null != _curNIC)
            {
                return true;
            }

            int nSelectedNIC = OConfiguration.instanceOf().GetSelectedNIC();
            if (nSelectedNIC < 0)
            {
                MessageBox.Show("There is no device selected.", "Error");
                return false;
            }
            if (nSelectedNIC >= CaptureDeviceList.Instance.Count)
            {
                MessageBox.Show("The selected device is not valid. Select device again", "Error");
                return false;
            }

            // clear all packet before starting capture
            _capturedPackets.Clear();
            // clear all current packet list
            _curPacketList.Clear();
            // clear ui
            lstPackets.Items.Clear();
            hexEdit.ByteProvider = null;

            _curNIC = CaptureDeviceList.Instance[nSelectedNIC];
            _threadObject = new Thread(_ThreadProc);
            _threadObject.Start();

            // Set up capture
            _eventPacketArrival = new PacketArrivalEventHandler(_OnPacketArrival); ;
            _eventCaptureStopped = new CaptureStoppedEventHandler(_OnCaptureStopped);
            _curNIC.OnPacketArrival += _eventPacketArrival;
            _curNIC.OnCaptureStopped += _eventCaptureStopped;
            _curNIC.Open();
            // start capture
            _curNIC.StartCapture();

            return true;
        }
예제 #44
0
        private void start_Click(object sender, EventArgs e)
        {
            if (DeviceList.SelectedItem == null)
                MessageBox.Show("Please choose a device to monitor");
            else if (CaptureOngoing)
                MessageBox.Show("Capturing...");
            else
            {
                CaptureOngoing = true;
                start.Enabled = false;
                reset.Enabled = true;
                pause.Enabled = true;
                save.Enabled = false;
                export.Enabled = false;

                device = devices[DeviceIndex];

                device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);// Registers new function to the event handler.

                int readTimeout = 10;
                device.Open(DeviceMode.Promiscuous, readTimeout);// Sets monitoring mode to promiscuous mode.
                device.Filter = FilterRule;
                FilterExp.Text = (FilterRule == "") ? "all pass" : FilterRule;
                device.StartCapture();
            }
        }
예제 #45
0
        private void StartCapture(int itemIndex)
        {
            packetCount = 0;
            device = CaptureDeviceList.Instance[itemIndex];
            packetStrings = new Queue<PacketWrapper>();
            bs = new BindingSource();
            dataGridView.DataSource = bs;
            LastStatisticsOutput = DateTime.Now;

            // start the background thread
            BackgroundThreadStop = false;
            backgroundThread = new System.Threading.Thread(BackgroundThread);
            backgroundThread.Start();

            // setup background capture
            arrivalEventHandler = new PacketArrivalEventHandler(device_OnPacketArrival);
            device.OnPacketArrival += arrivalEventHandler;
            captureStoppedEventHandler = new CaptureStoppedEventHandler(device_OnCaptureStopped);
            device.OnCaptureStopped += captureStoppedEventHandler;
            device.Open();

            // force an initial statistics update
            captureStatistics = device.Statistics;
            UpdateCaptureStatistics();

            // start the background capture
            device.StartCapture();

            // disable the stop icon since the capture has stopped
            startStopToolStripButton.Image = global::WinformsExample.Properties.Resources.stop_icon_enabled;
            startStopToolStripButton.ToolTipText = "Stop capture";
        }
예제 #46
0
파일: Form1.cs 프로젝트: jinpf/sniffer
 private void button1_Click(object sender, EventArgs e)
 {
     if (this.comboBox1.SelectedIndex >= 0)
     {
         try
         {
             //Register our handler function to the 'packet arrival' event
             _device = devices[this.comboBox1.SelectedIndex];
             _device.OnPacketArrival +=
                 new PacketArrivalEventHandler(device_OnPacketArrival);
             _device.Open();
             _device.Filter = textBox1.Text;
             for (int i = 0; i <= 5; i++)
                 PacketQueue[i].Clear();
             _device.StartCapture();
             try
             {
                 if (_Backgroundthread.IsAlive)
                 {
                     _Backgroundthread.Abort();
                 }
             }
             catch
             {
             }
             ThreadStart threadstart = new ThreadStart(Backgroundprocess);
             _Backgroundthread = new Thread(threadstart);
             _Backgroundthread.Start();      //开启后台线程
             textBox1.ReadOnly = true;
             button2.Enabled = true;
             button1.Enabled = false;
         }
         catch (Exception ex)
         {
             MessageBox.Show("过滤规则错误!"+ex.Message,"警告!");
         }
     }
     else
         MessageBox.Show("请选择网卡!","提示");
 }