예제 #1
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();
            }
        }
예제 #2
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)
            {
            }
        }
예제 #3
0
 private void StopCapture(ICaptureDevice pDevice)
 {
     if (_devices.Contains(pDevice))
         _devices.Remove(pDevice);
     pDevice.Close();
     pDevice.OnPacketArrival -= device_OnPacketArrival;
 }
예제 #4
0
        private void ProcessDevice(ICaptureDevice device)
        {
            var winpack = device as WinPcapDevice;

            if (device == null ||
                winpack?.Addresses.Count == 0)
            {
                return;
            }

            device.Open(DeviceMode.Promiscuous, ReadTimeoutMilliseconds);

            try
            {
                log.Info("Subscribing to: {0}-{1}", device.Description, device.MacAddress);
            }
            catch (Exception)
            {
                log.Info("Failed subscribption to: {0}", device.Description);
                return;
            }

            Subscribe(device);
            // tcpdump filter to capture only ARP Packets
            device.Filter = "arp";
            Action action = device.Capture;

            action.BeginInvoke(ar => action.EndInvoke(ar), null);
        }
예제 #5
0
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="deviceToCaptureInfo"></param>
        /// <param name="filter"></param>
        /// <param name="deviceMode"></param>
        /// <param name="reportMethods"></param>
        /// <param name="heartBeatDelay"></param>
        public BaseSensor(CaptureDeviceDescription deviceToCaptureInfo, string filter, DeviceMode deviceMode, List <ISensorReport> reportMethods, int heartBeatDelay, Enumerations.SensorMode sensorMode)
        {
            _sensorId = Guid.NewGuid();

            _lastTimeval = new PosixTimeval(0, 0);

            _reportMethods = reportMethods;

            _currentCaptureDevice = GetDeviceToCapture(deviceToCaptureInfo);
            _currentCaptureDevice.Open(deviceMode);
            if (!string.IsNullOrEmpty(filter))
            {
                _currentCaptureDevice.Filter = filter;
            }

            //attach listeners
            switch (sensorMode)
            {
            case Enumerations.SensorMode.PacketCapture:
                //_currentCaptureDevice.OnPacketArrival += new PacketArrivalEventHandler(_currentCaptureDevice_OnPacketArrival);
                _currentCaptureDevice.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
                break;

            case Enumerations.SensorMode.Statistics:
                var device = _currentCaptureDevice as WinPcapDevice;
                device.Mode              = CaptureMode.Statistics;
                device.OnPcapStatistics += device_OnPcapStatistics;
                break;
            }

            //start heartbeat timer
            StartHeartbeat(heartBeatDelay, reportMethods);
        }
예제 #6
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();
            }
        }
예제 #7
0
        public Form1()
        {
            InitializeComponent();

            //Get the list of devices
            devices = CaptureDeviceList.Instance;

            //Make sure at least one device is found
            if (devices.Count < 1)
            {
                MessageBox.Show("No capture devices found! You really messed up this one :(");
                Application.Exit();
            }

            //Add devices to the combo box
            foreach (ICaptureDevice dev in devices)
            {
                cmbDevices.Items.Add(dev.Description);
            }

            //Get the target device and display in combo box
            device          = devices[0];
            cmbDevices.Text = device.Description;

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

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

            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
        }
예제 #8
0
        public static void StartSniffing(ComboboxItem deviceItem)
        {
            PacketDataSource.Clear();
            var devices = CaptureDeviceList.Instance;

            currentDevice = devices.Where(fn => fn.Name.Contains(deviceItem.Value.ToString())).FirstOrDefault(); //find device by name ID
            if (currentDevice != null)
            {
                try
                {
                    //this needs more work, app is still slow and blocking
                    arrivalEventHandler            = new PacketArrivalEventHandler(device_OnPacketArrival);
                    currentDevice.OnPacketArrival += arrivalEventHandler;
                    BackgroundThreadStop           = false;
                    BackgroundThread = new System.Threading.Thread(RunBackgroundThread);
                    BackgroundThread.Start();

                    currentDevice.Open(DeviceMode.Promiscuous, 1000);

                    //string filter = "ip and tcp";
                    //device.Filter = filter;

                    // Start capture 'INFINTE' number of packets
                    currentDevice.Capture();
                } catch
                {
                }
            }
        }
예제 #9
0
        sendForm fSend;                          //create class variable

        public captureForm()
        {
            InitializeComponent();
            //Get list of devices
            devices = CaptureDeviceList.Instance;

            //Check for at least one device
            if (devices.Count < 1)
            {
                MessageBox.Show("No Capture Devices Found.");
                Application.Exit();
            }

            //Add the devices to the combo box, show description
            cmbDevices.DataSource    = devices;
            cmbDevices.DisplayMember = "Description";

            //Get the second device and display in combo box
            device          = devices[2];
            cmbDevices.Text = device.Description;

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

            //Open device for capturing
            int readTimeoutMilliseconds = 1000;

            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
        }
예제 #10
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";
        }
예제 #11
0
 private void ChooseDeviceBtn_Click(object sender, EventArgs e)
 {
     _currentDevice = _devices[DeviceList.SelectedIndex];
     // ReSharper disable LocalizableElement
     CurrentDeviceLbl.Text = "Current: " + _currentDevice.Description;
     // ReSharper restore LocalizableElement
 }
예제 #12
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);
         }
     }
 }
예제 #13
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;
     }
 }
예제 #14
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);
            }
        }
예제 #15
0
        private void ChooseDeviceBtn_Click(object sender, EventArgs e)
        {
            _currentDevice = _devices[DeviceList.SelectedIndex];
// ReSharper disable LocalizableElement
            CurrentDeviceLbl.Text = "Current: " + _currentDevice.Description;
// ReSharper restore LocalizableElement
        }
예제 #16
0
        public async Task <List <Device> > GetDevices(ICaptureDevice adapter, TimeSpan timeout)
        {
            var disposables = new CompositeDisposable();
            var transport   = new ProfinetEthernetTransport(adapter);

            transport.Open();
            transport.AddDisposableTo(disposables);

            var devices = new List <Device>();

            Observable.FromEventPattern <ProfinetEthernetTransport.OnDcpMessageHandler, ConnectionInfoEthernet, DcpMessageArgs>(h => transport.OnDcpMessage += h, h => transport.OnDcpMessage -= h)
            .Select(x => ConvertEventToDevice(x.Sender, x.EventArgs))
            .Where(device => devices != null)
            .Do(device => devices.Add(device))
            .Subscribe()
            .AddDisposableTo(disposables)
            ;

            transport.SendIdentifyBroadcast();

            await Task.Delay(timeout);

            disposables.Dispose();

            return(devices);
        }
예제 #17
0
 public static void Disconnect(IView view, Dictionary <IPAddress, PhysicalAddress> targetlist, IPAddress gatewayipaddress, PhysicalAddress gatewaymacaddress, string interfacefriendlyname)
 {
     engagedclientlist = new Dictionary <IPAddress, PhysicalAddress>();
     capturedevice     = (from devicex in CaptureDeviceList.Instance where ((SharpPcap.WinPcap.WinPcapDevice)devicex).Interface.FriendlyName == interfacefriendlyname select devicex).ToList()[0];
     capturedevice.Open();
     foreach (var target in targetlist)
     {
         IPAddress      myipaddress = ((SharpPcap.WinPcap.WinPcapDevice)capturedevice).Addresses[1].Addr.ipAddress; //possible critical point : Addresses[1] in hardcoding the index for obtaining ipv4 address
         ARPPacket      arppacketforgatewayrequest      = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), gatewayipaddress, capturedevice.MacAddress, target.Key);
         EthernetPacket ethernetpacketforgatewayrequest = new EthernetPacket(capturedevice.MacAddress, gatewaymacaddress, EthernetPacketType.Arp);
         ethernetpacketforgatewayrequest.PayloadPacket = arppacketforgatewayrequest;
         new Thread(() =>
         {
             disengageflag = false;
             DebugOutputClass.Print(view, "Spoofing target " + target.Value.ToString() + " @ " + target.Key.ToString());
             try
             {
                 while (!disengageflag)
                 {
                     capturedevice.SendPacket(ethernetpacketforgatewayrequest);
                 }
             }
             catch (PcapException ex)
             {
                 DebugOutputClass.Print(view, "PcapException @ DisconnectReconnect.Disconnect() [" + ex.Message + "]");
             }
             DebugOutputClass.Print(view, "Spoofing thread @ DisconnectReconnect.Disconnect() for " + target.Value.ToString() + " @ " + target.Key.ToString() + " is terminating.");
         }).Start();
         engagedclientlist.Add(target.Key, target.Value);
     }
     ;
 }
예제 #18
0
        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();
        }
예제 #19
0
 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         Action action = () =>
         {
             path = comboBox1.Text;
         };
         Invoke(action);
     }
     catch { }
     device = devices[comboBox1.SelectedIndex];
     while (dataGridView1.Rows.Count != 0)
     {
         dataGridView1.Rows.Remove(dataGridView1.Rows[0]);
     }
     toolStripStatusLabel1.Text = "Packets: capture is not started";
     toolStripStatusLabel2.Text = "";
     device.Open(DeviceMode.Promiscuous, 3000);
     string info;
     info = device.ToString().Substring(11);
     info = info.Substring(0, info.Length - 2);
     label1.Text = info;
     label2.Text = "";
     panel1.Focus();
 }
예제 #20
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();
        }
예제 #21
0
        public void Open(Uri uri)
        {
            if (this._captureDevice != null)
            {
                throw new InvalidOperationException("Only one call per object.");
            }

            this._uri = uri;

            // Capture file, not live interface
            if (this._uri.IsFile)
            {
                this._captureSize = new FileInfo(this._uri.AbsolutePath).Length;
            }

            this._captureDevice = this._captureDeviceFactory.CreateInstance(this._uri);

            if (this._captureDevice == null)
            {
                throw new InvalidOperationException($"There is no such device: {this._uri.AbsoluteUri}");
            }

            this._logger.LogInformation($"Opening> {this._uri}");

            if (this._captureDeviceFactory.DeviceMode == null)
            {
                this._captureDevice.Open();
            }
            else
            {
                this._captureDevice.Open((DeviceMode)this._captureDeviceFactory.DeviceMode);
            }
        }
예제 #22
0
        /// <summary>
        /// Constructor
        /// </summary>
        public MainForm()
        {
            InitializeComponent();

            //this.camera = new IpCamera(new Uri(this.ipCameraAddress));
            this.camera = new IpCamera(new Uri(this.ipMobileCamera));
        }
        private void ProcessPackets(ICaptureDevice dev,
                                    TcpConnectionManager tcpConnectionManager)
        {
            // reset the expected message index at the start of the test run
            expectedMessageIndex = 0;

            GetPacketStatus status;
            PacketCapture   e;

            while ((status = dev.GetNextPacket(out e)) == GetPacketStatus.PacketRead)
            {
                var rawCapture = e.GetPacket();
                var p          = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);

                var tcpPacket = p.Extract <TcpPacket>();

                // skip non-tcp packets, http is a tcp based protocol
                if (p == null)
                {
                    continue;
                }

                log.Debug("passing packet to TcpConnectionManager");
                tcpConnectionManager.ProcessPacket(rawCapture.Timeval,
                                                   tcpPacket);
            }

            // did we get all of the messages?
            Assert.Equal(expectedMessages.Count, expectedMessageIndex);
        }
예제 #24
0
        public xbs_sniffer(ICaptureDevice dev, bool use_special_mac_filter, List<PhysicalAddress> filter_special_macs, bool only_forward_special_macs, xbs_node_list node_list, xbs_nat NAT, GatewayIPAddressInformationCollection gateways, bool exclude_gateway_ips)
        {
            this.NAT = NAT;
            this.pdev_filter_use_special_macs = use_special_mac_filter;
            if (filter_special_macs!=null)
                this.pdev_filter_special_macs = filter_special_macs;
            this.pdev_filter_only_forward_special_macs = only_forward_special_macs;
            this.pdev_filter_exclude_gatway_ips = exclude_gateway_ips;
            create_gateway_filter(gateways);
            injected_macs_hash.Capacity = 40;
            sniffed_macs_hash.Capacity = 10;
            sniffed_macs.Capacity = 10;

            this.node_list = node_list;

            if (!(dev is SharpPcap.LibPcap.LibPcapLiveDevice))
                throw new ArgumentException("pcap caputure device is not a LibPcapLiveDevice");
            this.pdev = (SharpPcap.LibPcap.LibPcapLiveDevice)dev;
            pdev.OnPacketArrival +=
                new PacketArrivalEventHandler(OnPacketArrival);
            pdev.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            setPdevFilter();

            if (System.Environment.OSVersion.Platform == PlatformID.Win32NT && pdev is SharpPcap.WinPcap.WinPcapDevice)
                ((SharpPcap.WinPcap.WinPcapDevice)pdev).MinToCopy = 10;

            xbs_messages.addInfoMessage(" - sniffer created on device " + pdev.Description, xbs_message_sender.SNIFFER);

            dispatcher_thread = new Thread(new ThreadStart(dispatcher));
            dispatcher_thread.IsBackground = true;
            dispatcher_thread.Priority = ThreadPriority.AboveNormal;
            dispatcher_thread.Start();
        }
예제 #25
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++;
            }
        }
예제 #26
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();
        }
예제 #27
0
 public RawCapture(ICaptureDevice device, ICaptureHeader header, System.ReadOnlySpan <byte> data)
 {
     this.LinkLayerType = device.LinkType;
     this.Timeval       = header.Timeval;
     this.Data          = data.ToArray();
     this.PacketLength  = Data?.Length ?? 0;
 }
예제 #28
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);
        }
        public FlowMeasureDevice(string ip)
        {
            localIP = ip;
            int currentDevice;

            var Devices = CaptureDeviceList.New();

            for (currentDevice = 0; currentDevice < Devices.Count; currentDevice++)
            {
                if (Devices[currentDevice].ToString().IndexOf(ip) != -1)
                {
                    break;
                }
            }

            SendDevice = (ICaptureDevice)CaptureDeviceList.New()[currentDevice];
            SendDevice.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalSend);
            SendDevice.Open(DeviceMode.Promiscuous, 1000);
            SendDevice.Filter = "src host " + ip;

            RecvDevice = (ICaptureDevice)CaptureDeviceList.New()[currentDevice];
            RecvDevice.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalRecv);
            RecvDevice.Open(DeviceMode.Promiscuous, 1000);
            RecvDevice.Filter = "dst host " + ip;

            NetSendBytes = 0;
            NetRecvBytes = 0;
            isUsed       = false;
        }
예제 #30
0
파일: Form1.cs 프로젝트: yanggis/sniffer
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.is_saved == false && this.packets.Count > 0)
            {
                if (MessageBox.Show("不保存并重新抓包?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }
            }
            //设置保存标志位
            this.is_saved = false;
            this.button1.Enabled = false;
            this.button5.Enabled = false;
            this.button8.Enabled = false;
            this.comboBox1.Enabled = false;
            this.button2.Enabled = true;
            //清除之前的数据
            this.packets = new ArrayList();
            this.files = new ArrayList();
            this.dataGridView1.Rows.Clear();
            this.restruct_get.Rows.Clear();
            this.search_keyword.Text = "";
            //读取要监听的网卡
            int eth = System.Int32.Parse(this.comboBox1.SelectedValue.ToString());
            var devices = CaptureDeviceList.Instance;
            this.device = devices[eth];

            this.readTimeoutMilliseconds = 1000;

            Thread newThread = new Thread(new ThreadStart(threadHandler));
            newThread.Start();
        }
예제 #31
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);
        }
예제 #32
0
 public PacketReader(ICaptureDevice device, bool dumpVideo)
 {
     _device = device;
     this.dumpVideo = dumpVideo;
     _buffers[0] = new RingBuffer(Frame.FrameDirection.ToDrone);
     _buffers[1] = new RingBuffer(Frame.FrameDirection.ToController);
 }
예제 #33
0
        public frmCapture()
        {
            InitializeComponent();

            //Get the list of devices
            devices = CaptureDeviceList.Instance;

            //Make sure there is at least one device
            if (devices.Count < 1)
            {
                MessageBox.Show("No Capture Devices Found!");
                Application.Exit();
            }

            //Add devices to combobox
            foreach (ICaptureDevice dev in devices)
            {
                cmbDevices.Items.Add(dev.Description);
            }

            //Get the 2nd device and display In combo box
            device          = devices[1];
            cmbDevices.Text = device.Description;

            //register 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);
        }
예제 #34
0
 public LimiterClass(Device device)
 {
     this.device   = device;
     capturedevice = CaptureDeviceList.New()[Properties.Settings.Default.AdapterName];
     TargetMAC     = GetClientList.GetMACString(device.MAC);
     GatewayMAC    = GetClientList.GetMACString(device.GatewayMAC);
 }
예제 #35
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();
            }
        }
예제 #36
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();
            }
        }
예제 #37
0
 public MyDevice(PacketDevice device, string macAddress, string ipAddress, int id, ICaptureDevice capDevice, PacketCommunicator communicator)
 {
     this.addresses = new List<Address>();
     this.device = device;
     this.id = id;
     this.macAddress = macAddress;
     this.ipAddress = ipAddress;
     this.capDevice = capDevice;
     this.communicator = communicator;
 }
예제 #38
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();
        }
        public PacketCaptureThread(ICaptureDevice captureDevice, ToolUI toolUI)
        {
            //Store passed objects
            this.captureDevice = captureDevice;
            this.toolUI = toolUI;

            //Start the thread
            packetCaptureThread = new Thread(PacketCaptureThreadStart);
            #if DEBUG
            packetCaptureThread.Name = "Packet Capture Thread";
            #endif
            packetCaptureThread.Start();
        }
예제 #40
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) { };
        }
예제 #41
0
파일: VNESBase.cs 프로젝트: pmartins/VNES
        public bool StartEquipment(ICaptureDevice device)
        {
            bool startSuccess = false;

            if (device!=null)
            {
                equipNetworkDevice = device;

                device.Open(DeviceMode.Promiscuous, ReadTimeOutMs);
                isWorking = true;

                device.Filter = this.filter;

                Thread thread = new Thread(new ParameterizedThreadStart(this.DoCapture));
                thread.Start(device);
            }

            return startSuccess;
        }
예제 #42
0
파일: Capturing.cs 프로젝트: ren85/catcher
        public void StartCapturing(int device_choice)
        {
            // If no devices were found print an error
            if(devices.Count < 1)
            {
                throw new Exception("No devices were found on this machine");
            }

            device = devices[device_choice];

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

            // Open the device for capturing
            device.Open();

            // Start capture 'INFINTE' number of packets
            device.Capture();
        }
예제 #43
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();
        }
예제 #44
0
        public MainWindow()
        {
            _cardDetector = new AForgeCardDetector();

            DataContext = this;

            InitializeComponent();

            AForgeCaptureDeviceFactory captureDeviceFactory = new AForgeCaptureDeviceFactory();
            _captureDevice = captureDeviceFactory.First();
            if (_captureDevice == null)
                return;

            _captureDevice.Frames
                .Sample(TimeSpan.FromSeconds(1 / 30))
                .Select(Process)
                .ObserveOn(Webcam)
                .Subscribe(Display);

            _captureDevice.Start();
        }
예제 #45
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;
        }
예제 #46
0
        private void OnOpenFile(object sender, ExecutedRoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
            ofd.Filter = "Text Files (*.sniffer)|*.sniffer";
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == true)
            {
                if (packets != null)
                {
                    packets.Clear();
                }

                if (rawCapturesList != null)
                {
                    rawCapturesList.Clear();
                }
                try
                {
                    ClearBoard();

                    this.readerDevice = new CaptureFileReaderDevice(ofd.FileName);
                    this.readerDevice.OnPacketArrival += new PacketArrivalEventHandler(readerDevice_OnPacketArrival);
                    this.readerDevice.Open();
                    this.readerDevice.Capture();
                    this.readerDevice.OnPacketArrival -= new PacketArrivalEventHandler(readerDevice_OnPacketArrival);
                }
                catch { }
                // Open the device for capturing
            }
        }
예제 #47
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();
            }
        }
예제 #48
0
 private void Init()
 {
     this.PacketCount = 0;
     this.device = null;
     this.continueGetPacket = false;
     this.filterRule = "";
     this.canStopListening = false;
     this.selectedRawCapture = null;
     this.captureMode = 1;//default is p mode, 0 is normal mode. 1 is p mode
 }
예제 #49
0
 void interfacesView_ChooseInterfaceEvent(object sender, int interfaceIndex, int _captureMode)
 {
     /* Retrieve the device list */
     var devices = CaptureDeviceList.Instance;
     device = devices[interfaceIndex];
     this.captureMode = _captureMode;
 }
예제 #50
0
        private void numericUpDown1_ValueChanged(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;

            deviceNumber = (int)numericUpDown1.Value;

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

            Console.WriteLine("-- Set device to listening on {0}", deviceMasterSent.Description);
        }
예제 #51
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;
        }
예제 #52
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";
        }
예제 #53
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;
        }
예제 #54
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("请选择网卡!","提示");
 }
예제 #55
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();
 }
예제 #56
0
파일: Capturing.cs 프로젝트: ren85/catcher
 public void StopCapturing()
 {
     if(device != null)
     {
         device.StopCapture();
         device.Close();
         device = null;
     }
 }
예제 #57
0
파일: Form1.cs 프로젝트: jinpf/sniffer
 private void Shutdown()
 {
     if(_device != null)
     {
         _device.StopCapture();
         _device.Close();
         _device = null;
     //                _Backgroundthread.Abort();
     //                _threadabort = true;
         textBox1.ReadOnly = false;
     //                MessageBox.Show(PacketQueue.Capacity.ToString()+" "+PacketQueue.Count.ToString());
         button1.Enabled = true;
         button2.Enabled = false;
     }
 }
예제 #58
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();
        }
예제 #59
0
파일: Form1.cs 프로젝트: Ch0wW/XBSlink
        // -----------------------------------------------------

        private NetworkInterface getNetworkInterfaceForPDEV(ICaptureDevice pdev)
        {
            List<PcapAddress> addresses = new List<PcapAddress>();
            PhysicalAddress mac = null;
            if (pdev is LibPcapLiveDevice)
            {
                foreach (PcapAddress pa in ((LibPcapLiveDevice)pdev).Addresses)
                    if (pa.Addr.type == Sockaddr.AddressTypes.HARDWARE)
                        mac = pa.Addr.hardwareAddress;
            }
            else
            {
                return null;
            }
            if (mac == null)
                return null;
            NetworkInterface[] network_interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface ni in network_interfaces)
            {
                if (ni.GetPhysicalAddress().Equals(mac))
                    return ni;
            }
            return null;
        }
예제 #60
0
 public DeviceOption(string name, ICaptureDevice device)
 {
     Name = name;
     Value = device;
 }