コード例 #1
0
ファイル: GetClientList.cs プロジェクト: Tupiet/ByeWifi
        /// <summary>
        /// Populates listview with machines connected to the LAN
        /// </summary>
        /// <param name="view"></param>
        /// <param name="interfacefriendlyname"></param>
        public static void GetAllClients(IView view, string interfacefriendlyname)
        {
            DebugOutputClass.Print(view, "Recarga para escanear");
            #region initialization
            view.MainForm.Invoke(new Action(() => view.ToolStripStatusScan.Text       = "Por favor, espere..."));
            view.MainForm.Invoke(new Action(() => view.ToolStripProgressBarScan.Value = 0));
            if (capturedevice != null)
            {
                try
                {
                    capturedevice.StopCapture(); //stop previous capture
                    capturedevice.Close();       //close previous instances
                }
                catch (PcapException ex)
                {
                    DebugOutputClass.Print(view, "Exception at GetAllClients while trying to capturedevice.StopCapture() or capturedevice.Close() [" + ex.Message + "]");
                }
            }
            clientlist = new Dictionary <IPAddress, PhysicalAddress>(); //this is preventing redundant entries into listview and for counting total clients
            view.ListView1.Items.Clear();
            #endregion

            CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance;
            capturedevicelist.Refresh();                                                                          //crucial for reflection of any network changes
            capturedevice = (from devicex in capturedevicelist where ((SharpPcap.WinPcap.WinPcapDevice)devicex).Interface.FriendlyName == interfacefriendlyname select devicex).ToList()[0];
            capturedevice.Open(DeviceMode.Promiscuous, 1000);                                                     //open device with 1000ms timeout
            IPAddress myipaddress = ((SharpPcap.WinPcap.WinPcapDevice)capturedevice).Addresses[1].Addr.ipAddress; //possible critical point : Addresses[1] in hardcoding the index for obtaining ipv4 address

            #region Sending ARP requests to probe for all possible IP addresses on LAN
            new Thread(() =>
            {
                try
                {
                    for (int ipindex = 1; ipindex <= 255; ipindex++)
                    {
                        ARPPacket arprequestpacket    = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(GetRootIp(myipaddress) + ipindex), capturedevice.MacAddress, myipaddress);
                        EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                        ethernetpacket.PayloadPacket  = arprequestpacket;
                        capturedevice.SendPacket(ethernetpacket);
                    }
                }
                catch (Exception ex)
                {
                    DebugOutputClass.Print(view, "Exception at GetClientList.GetAllClients() inside new Thread(()=>{}) while sending packets probably because old thread was still running while capturedevice was closed due to subsequent refresh [" + ex.Message + "]");
                }
            }).Start();
            #endregion

            #region Retrieving ARP packets floating around and finding out the senders' IP and MACs
            capturedevice.Filter = "arp";
            RawCapture rawcapture   = null;
            long       scanduration = 5000;
            new Thread(() =>
            {
                try
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while ((rawcapture = capturedevice.GetNextPacket()) != null && stopwatch.ElapsedMilliseconds <= scanduration)
                    {
                        Packet packet       = Packet.ParsePacket(rawcapture.LinkLayerType, rawcapture.Data);
                        ARPPacket arppacket = (ARPPacket)packet.Extract(typeof(ARPPacket));
                        if (!clientlist.ContainsKey(arppacket.SenderProtocolAddress) && arppacket.SenderProtocolAddress.ToString() != "0.0.0.0" && areCompatibleIPs(arppacket.SenderProtocolAddress, myipaddress))
                        {
                            clientlist.Add(arppacket.SenderProtocolAddress, arppacket.SenderHardwareAddress);
                            view.ListView1.Invoke(new Action(() =>
                            {
                                view.ListView1.Items.Add(new ListViewItem(new string[] { clientlist.Count.ToString(), arppacket.SenderProtocolAddress.ToString(), GetMACString(arppacket.SenderHardwareAddress), "Activado", ApplicationSettingsClass.GetSavedClientNameFromMAC(GetMACString(arppacket.SenderHardwareAddress)) }));
                            }));
                            //Debug.Print("{0} @ {1}", arppacket.SenderProtocolAddress, arppacket.SenderHardwareAddress);
                        }
                        int percentageprogress = (int)((float)stopwatch.ElapsedMilliseconds / scanduration * 100);
                        view.MainForm.Invoke(new Action(() => view.ToolStripStatusScan.Text       = "Escaneando... " + percentageprogress + "%"));
                        view.MainForm.Invoke(new Action(() => view.ToolStripProgressBarScan.Value = percentageprogress));
                        //Debug.Print(packet.ToString() + "\n");
                    }
                    stopwatch.Stop();
                    view.MainForm.Invoke(new Action(() => view.ToolStripStatusScan.Text       = clientlist.Count.ToString() + " dispositivo(s) encontrados"));
                    view.MainForm.Invoke(new Action(() => view.ToolStripProgressBarScan.Value = 100));
                    BackgroundScanStart(view, interfacefriendlyname); //start passive monitoring
                }
                catch (PcapException ex)
                {
                    DebugOutputClass.Print(view, "PcapException @ GetClientList.GetAllClients() @ new Thread(()=>{}) while retrieving packets [" + ex.Message + "]");
                    view.MainForm.Invoke(new Action(() => view.ToolStripStatusScan.Text       = "Recarga para escanear"));
                    view.MainForm.Invoke(new Action(() => view.ToolStripProgressBarScan.Value = 0));
                }
                catch (Exception ex)
                {
                    DebugOutputClass.Print(view, ex.Message);
                }
            }).Start();
            #endregion
        }
コード例 #2
0
ファイル: CaptureService.cs プロジェクト: valeIT/swtor-emu
 public static void StopCapture()
 {
     captureDevice.StopCapture();
 }
コード例 #3
0
ファイル: Scanner.cs プロジェクト: reewardius/NetStalker
        /// <summary>
        /// Populates the list with devices connected on LAN
        /// </summary>
        /// <param name="view">UI controls</param>
        /// <param name="InterfaceFriendlyName"></param>
        public static void StartScan(IView view, string InterfaceFriendlyName)
        {
            #region initialization

            if (capturedevice != null)
            {
                GatewayCalled          = false;
                BackgroundScanDisabled = true;
                capturedevice.StopCapture();
                capturedevice.Close();
                capturedevice = null;
            }
            else
            {
                ClientList   = new Dictionary <IPAddress, PhysicalAddress>();
                Main.Devices = new ConcurrentDictionary <IPAddress, Device>();
            }

            #endregion

            //Get list of interfaces
            CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance;
            //crucial for reflection on any network changes
            capturedevicelist.Refresh();
            capturedevice = (from devicex in capturedevicelist where ((NpcapDevice)devicex).Interface.FriendlyName == InterfaceFriendlyName select devicex).ToList()[0];
            //open device in promiscuous mode with 1000ms timeout
            capturedevice.Open(DeviceMode.Promiscuous, 1000);
            //Arp filter
            capturedevice.Filter = "arp";

            IPAddress myipaddress = AppConfiguration.LocalIp;

            //Probe for active devices on the network
            if (DiscoveryTimer == null)
            {
                StartDescoveryTimer();
            }

            #region Retrieving ARP packets floating around and find out the sender's IP and MAC

            //Scan duration
            long       scanduration = 8000;
            RawCapture rawcapture   = null;

            //Main scanning task
            ScannerTask = Task.Run(() =>
            {
                try
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while ((rawcapture = capturedevice.GetNextPacket()) != null && stopwatch.ElapsedMilliseconds <= scanduration)
                    {
                        Packet packet       = Packet.ParsePacket(rawcapture.LinkLayerType, rawcapture.Data);
                        ArpPacket ArpPacket = packet.Extract <ArpPacket>();
                        if (!ClientList.ContainsKey(ArpPacket.SenderProtocolAddress) && ArpPacket.SenderProtocolAddress.ToString() != "0.0.0.0" && Tools.AreCompatibleIPs(ArpPacket.SenderProtocolAddress, myipaddress, AppConfiguration.NetworkSize))
                        {
                            ClientList.Add(ArpPacket.SenderProtocolAddress, ArpPacket.SenderHardwareAddress);

                            string mac = Tools.GetMACString(ArpPacket.SenderHardwareAddress);
                            string ip  = ArpPacket.SenderProtocolAddress.ToString();
                            var device = new Device
                            {
                                IP           = ArpPacket.SenderProtocolAddress,
                                MAC          = PhysicalAddress.Parse(mac.Replace(":", "")),
                                DeviceName   = "Resolving",
                                ManName      = "Getting information...",
                                DeviceStatus = "Online"
                            };

                            //Add device to UI list
                            view.ListView1.BeginInvoke(new Action(() => { view.ListView1.AddObject(device); }));

                            //Add device to main device list
                            _ = Main.Devices.TryAdd(ArpPacket.SenderProtocolAddress, device);

                            //Get hostname and mac vendor for the current device
                            _ = Task.Run(async() =>
                            {
                                try
                                {
                                    #region Get Hostname

                                    IPHostEntry hostEntry = await Dns.GetHostEntryAsync(ip);
                                    device.DeviceName     = hostEntry?.HostName ?? ip;

                                    #endregion

                                    #region Get MacVendor

                                    var Name       = VendorAPI.GetVendorInfo(mac);
                                    device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                    #endregion

                                    view.ListView1.BeginInvoke(new Action(() => { view.ListView1.UpdateObject(device); }));
                                }
                                catch (Exception ex)
                                {
                                    try
                                    {
                                        if (ex is SocketException)
                                        {
                                            var Name       = VendorAPI.GetVendorInfo(mac);
                                            device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                            view.ListView1.BeginInvoke(new Action(() =>
                                            {
                                                device.DeviceName = ip;
                                                view.ListView1.UpdateObject(device);
                                            }));
                                        }
                                        else
                                        {
                                            view.MainForm.BeginInvoke(
                                                new Action(() =>
                                            {
                                                device.DeviceName = ip;
                                                device.ManName    = "Error";
                                                view.ListView1.UpdateObject(device);
                                            }));
                                        }
                                    }
                                    catch
                                    {
                                    }
                                }
                            });
                        }

                        int percentageprogress = (int)((float)stopwatch.ElapsedMilliseconds / scanduration * 100);

                        view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning " + percentageprogress + "%"));
                    }

                    stopwatch.Stop();
                    view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = ClientList.Count.ToString() + " device(s) found"));

                    //Initial scanning is over now we start the background scan.
                    Main.OperationIsInProgress = false;

                    //Start passive monitoring
                    BackgroundScanStart(view);
                }
                catch
                {
                    //Show an error in the UI in case something went wrong
                    try
                    {
                        view.MainForm.BeginInvoke(new Action(() =>
                        {
                            view.StatusLabel.Text = "Error occurred";
                            view.PictureBox.Image = Properties.Resources.color_error;
                        }));
                    }
                    catch { } //Swallow exception when the user closes the app during the scan operation
                }
            });

            #endregion
        }
コード例 #4
0
        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();
            }
        }
コード例 #5
0
 public void StopCapture()
 {
     device.StopCapture();
     device.Close();
 }
コード例 #6
0
ファイル: Main.cs プロジェクト: zhouzu/packetnet-connections
        public static void Main(string[] args)
        {
            // Print SharpPcap version
            string ver = SharpPcap.Version.VersionString;

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

            // Retrieve the device list
            var devices = SharpPcap.LibPcap.LibPcapLiveDeviceList.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();
            Console.WriteLine("The following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------");
            Console.WriteLine();

            int i = 0;

            // Print out the devices
            foreach (SharpPcap.LibPcap.LibPcapLiveDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
                i++;
            }

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

            ICaptureDevice device = devices[i];

            tcpConnectionManager.OnConnectionFound += HandleTcpConnectionManagerOnConnectionFound;

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

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

            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

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

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

            // Wait for 'Enter' from the user.
            Console.ReadLine();

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

            Console.WriteLine("-- Capture stopped.");
        }
コード例 #7
0
 public void StopCapture()
 {
     device.StopCapture();
     device.Close();
     captureIp = "";
 }
コード例 #8
0
        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(); }
        }
コード例 #9
0
 private void on_stop_event(object sender, EventArgs e)
 {
     selected.StopCapture();
     selected.Close();
 }
コード例 #10
0
 internal void Stop()
 {
     _device.StopCapture();
     _device.Close();
 }
コード例 #11
0
 public void StopListening()
 {
     captureDevice.StopCapture();
 }
コード例 #12
0
ファイル: Monitor.cs プロジェクト: atom-chen/fknsg
 public static void Close()
 {
     CurrentDevice.StopCapture();
     CurrentThread.Interrupt();
     CurrentDevice.Close();
 }
コード例 #13
0
        public static void getPacket(Packet packet)
        {
            List <NetworkInterface> INTERFACES = new List <NetworkInterface> {
            };

            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                INTERFACES.Add(nic);
            }

            for (int i = 0; i < INTERFACES.Count; i++)
            {
                Console.WriteLine("\n\n\t" + i + ". " + INTERFACES[i].Name);
            }

            bool flag = true;
            int  number;
            CaptureDeviceList deviceList = CaptureDeviceList.Instance;
            string            num;

            while (flag)
            {
                while (true)
                {
                    Console.Write("\n\nEnter interface number(Enter 9 for exit): ");
                    num = Console.ReadLine();

                    if (!(int.TryParse(num, out number)))
                    {
                        continue;
                    }

                    number = Convert.ToInt32(num);

                    if (!(number > INTERFACES.Count || number < 0))
                    {
                        break;
                    }
                }

                if (number == INTERFACES.Count)
                {
                    flag = false;
                }

                else
                {
                    Console.WriteLine();
                    foreach (ICaptureDevice dev in CaptureDeviceList.Instance)
                    {
                        if (devName(dev.Name) == INTERFACES[number].Id)
                        {
                            Console.WriteLine(dev.Name);
                            ICaptureDevice captured = dev;
                            captured.Open();

                            try {
                                captured.SendPacket(packet);
                                Console.WriteLine("\n-- Packet sent successfuly");
                                Console.WriteLine("\nPress Enter");
                            }

                            catch (Exception e) {
                                Console.WriteLine("--" + e.Message);
                            }

                            Console.ReadLine();
                            captured.StopCapture();
                            Console.WriteLine("-- Device closed");
                        }
                    }
                }
            }
        }
コード例 #14
0
        /**
         * Function which Extract Packet
         * take info (about source and destination -> ports, address(which is converted to DN))
         * and at the end of function, there is print function for print sniffed packet
         */
        void gotPacket(object sender, CaptureEventArgs e)
        {
            var time = e.Packet.Timeval.Date;
            var len  = e.Packet.Data.Length;

            var packet    = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            var tcpPacket = packet.Extract <PacketDotNet.TcpPacket>();
            var udpPacket = packet.Extract <PacketDotNet.UdpPacket>();

            countPackets++;
            if (number < countPackets)
            {
                device.Close();
                device.StopCapture();
                Environment.Exit(0);
            }

            /**
             * We detected that we got udp packet, so it execute this part of code
             * which take source and destination address / port
             * also take hostName (if exists) from function findHostName
             * and print it as a info of packet
             */

            if (udpPacket != null)
            {
                var Packet = (PacketDotNet.IPPacket)udpPacket.ParentPacket;

                var src     = Packet.SourceAddress;
                var dst     = Packet.DestinationAddress;
                var srcPort = udpPacket.SourcePort;
                var dstPort = udpPacket.DestinationPort;

                string hostnameSrc = findHostName(src.ToString());;
                string hostnameDst = findHostName(dst.ToString());;

                Console.WriteLine("{0}:{1}:{2}.{3} {4} : {5} > {6} : {7}\n",
                                  time.Hour, time.Minute, time.Second, time.Millisecond, hostnameSrc, srcPort, hostnameDst, dstPort);

                int length = len - udpPacket.PayloadData.Length; //calculate length of header data

                firstNum  = 0;
                secondNum = 0;
                thirdNum  = 0;
                fourthNum = 0;

                /**
                 * THIS PART OF CODE, SEPARATE HEADERS AND
                 * OPTIONS IN PACKET AND PRINT PRINTABLE ASCII CHARACTERS
                 * IF IS NONPRINTABLE CHAR THERE, IT WILL PRINT AS DOT
                 */
                string[] udpfile = fillSeparatedParts(0, length, udpPacket.BytesSegment);
                createAsciiChars(udpfile);
                Console.WriteLine();

                if (udpPacket.PayloadData.Length > 0)
                {
                    string[] udpfile2 = fillSeparatedParts(length, len, udpPacket.PayloadDataSegment);
                    if (udpfile2.Length > 0)
                    {
                        createAsciiChars(udpfile2);
                    }
                    Console.WriteLine();
                }
                Console.WriteLine();
            }

            /**
             * We detected that we got tcp packet, so it execute this part of code
             * which take source and destination address / port
             * also take hostName (if exists) from function findHostName
             * and print it as a info of packet
             */

            if (tcpPacket != null)
            {
                var Packet = (PacketDotNet.IPPacket)tcpPacket.ParentPacket;

                var src     = Packet.SourceAddress;
                var dst     = Packet.DestinationAddress;
                var srcPort = tcpPacket.SourcePort;
                var dstPort = tcpPacket.DestinationPort;

                string hostnameSrc = findHostName(src.ToString());
                string hostnameDst = findHostName(dst.ToString());

                Console.WriteLine("{0}:{1}:{2}.{3} {4} : {5} > {6} : {7}\n",
                                  time.Hour, time.Minute, time.Second, time.Millisecond, hostnameSrc, srcPort, hostnameDst, dstPort);

                /**
                 * THIS PART OF CODE, SEPARATE HEADERS AND
                 * OPTIONS IN PACKET AND PRINT PRINTABLE ASCII CHARACTERS
                 * IF IS NONPRINTABLE CHAR THERE, IT WILL PRINT AS DOT
                 */
                int length = len - tcpPacket.PayloadData.Length; //calculate length of header data

                firstNum  = 0;
                secondNum = 0;
                thirdNum  = 0;
                fourthNum = 0;

                string[] tcpfile = fillSeparatedParts(0, length, tcpPacket.BytesSegment);
                createAsciiChars(tcpfile);
                Console.WriteLine();

                if (tcpPacket.PayloadData.Length > 0)
                {
                    string[] tcpfile2 = fillSeparatedParts(length, len, tcpPacket.PayloadDataSegment);
                    if (tcpfile2.Length > 0)
                    {
                        createAsciiChars(tcpfile2);
                    }
                    Console.WriteLine();
                }
                Console.WriteLine();
            }
        }
コード例 #15
0
        public static void GetAllClients(IView view, string interfacefriendlyname)
        {
            #region initialization
            if (capturedevice != null)
            {
                try
                {
                    capturedevice.StopCapture(); //stop previous capture
                    capturedevice.Close();       //close previous instances
                    StopFlag      = true;
                    GatewayCalled = false;
                    capturedevice.OnPacketArrival += null;
                    Main.checkboxcanbeclicked      = false;
                    StopTheLoadingBar(view);
                }
                catch (PcapException)
                {
                }
            }
            clientlist = new Dictionary <IPAddress, PhysicalAddress>();

            #endregion

            CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance;
            capturedevicelist.Refresh();                      //crucial for reflection of any network changes
            capturedevice = (from devicex in capturedevicelist where ((SharpPcap.WinPcap.WinPcapDevice)devicex).Interface.FriendlyName == interfacefriendlyname select devicex).ToList()[0];
            capturedevice.Open(DeviceMode.Promiscuous, 1000); //open device with 1000ms timeout
            capturedevice.Filter = "arp";
            IPAddress myipaddress = IPAddress.Parse(NetStalker.Properties.Settings.Default.localip);

            Size = NetStalker.Properties.Settings.Default.NetSize;
            var Root = GetRoot(myipaddress, Size);
            if (string.IsNullOrEmpty(Root))
            {
                try
                {
                    view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = "Network Error"));
                    return;
                }
                catch (Exception)
                {
                }
            }

            #region Sending ARP requests to probe for all possible IP addresses on LAN
            new Thread(() =>
            {
                try
                {
                    if (Size == 1)
                    {
                        for (int ipindex = 1; ipindex <= 255; ipindex++)
                        {
                            ARPPacket arprequestpacket    = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(Root + ipindex), capturedevice.MacAddress, myipaddress);
                            EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                            ethernetpacket.PayloadPacket  = arprequestpacket;
                            capturedevice.SendPacket(ethernetpacket);
                        }
                    }

                    else if (Size == 2)
                    {
                        for (int i = 1; i <= 255; i++)
                        {
                            for (int j = 1; j <= 255; j++)
                            {
                                ARPPacket arprequestpacket    = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(Root + i + '.' + j), capturedevice.MacAddress, myipaddress);
                                EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                                ethernetpacket.PayloadPacket  = arprequestpacket;
                                capturedevice.SendPacket(ethernetpacket);
                                if (!GatewayCalled)
                                {
                                    ARPPacket ArpForGateway        = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), GatewayIP, capturedevice.MacAddress, myipaddress);//???
                                    EthernetPacket EtherForGateway = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                                    EtherForGateway.PayloadPacket  = ArpForGateway;
                                    capturedevice.SendPacket(EtherForGateway);
                                    GatewayCalled = true;
                                }
                            }
                        }
                    }

                    else if (Size == 3)
                    {
                        if (MetroMessageBox.Show(view.MainForm,
                                                 "The network you're scanning is very large, it will take approximately 20 hours before the scanner can find all the devices, proceed?",
                                                 "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                        {
                            for (int i = 1; i <= 255; i++)
                            {
                                for (int j = 1; j <= 255; j++)
                                {
                                    for (int k = 1; k <= 255; k++)
                                    {
                                        ARPPacket arprequestpacket = new ARPPacket(ARPOperation.Request,
                                                                                   PhysicalAddress.Parse("00-00-00-00-00-00"),
                                                                                   IPAddress.Parse(Root + i + '.' + j + '.' + k), capturedevice.MacAddress,
                                                                                   myipaddress);
                                        EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress,
                                                                                           PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                                        ethernetpacket.PayloadPacket = arprequestpacket;
                                        capturedevice.SendPacket(ethernetpacket);
                                        if (!GatewayCalled)
                                        {
                                            ARPPacket ArpForGateway        = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), GatewayIP, capturedevice.MacAddress, myipaddress); //???
                                            EthernetPacket EtherForGateway = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);                  //???
                                            EtherForGateway.PayloadPacket  = ArpForGateway;
                                            capturedevice.SendPacket(EtherForGateway);
                                            GatewayCalled = true;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                catch (Exception)
                {
                }
            }).Start();
            #endregion

            #region Retrieving ARP packets floating around and finding out the senders' IP and MACs
            capturedevice.Filter = "arp";
            RawCapture rawcapture   = null;
            long       scanduration = 8000;
            new Thread(() =>
            {
                try
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while ((rawcapture = capturedevice.GetNextPacket()) != null && stopwatch.ElapsedMilliseconds <= scanduration)
                    {
                        Packet packet       = Packet.ParsePacket(rawcapture.LinkLayerType, rawcapture.Data);
                        ARPPacket arppacket = (ARPPacket)packet.Extract(typeof(ARPPacket));
                        if (!clientlist.ContainsKey(arppacket.SenderProtocolAddress) && arppacket.SenderProtocolAddress.ToString() != "0.0.0.0" && areCompatibleIPs(arppacket.SenderProtocolAddress, myipaddress, Size))
                        {
                            clientlist.Add(arppacket.SenderProtocolAddress, arppacket.SenderHardwareAddress);
                            view.ListView1.Invoke(new Action(() =>
                            {
                                string mac = GetMACString(arppacket.SenderHardwareAddress);
                                int id     = clientlist.Count - 1;
                                string ip  = arppacket.SenderProtocolAddress.ToString();
                                var obj    = new Device();
                                new Thread(() =>
                                {
                                    try
                                    {
                                        ipp = ip;

                                        IPHostEntry hostEntry = Dns.GetHostEntry(ip);

                                        view.ListView1.BeginInvoke(new Action(() =>
                                        {
                                            obj.DeviceName = hostEntry.HostName;
                                            view.ListView1.UpdateObject(obj);
                                        }));
                                    }
                                    catch (Exception)
                                    {
                                        try
                                        {
                                            view.ListView1.BeginInvoke(new Action(() =>
                                            {
                                                obj.DeviceName = ip;
                                                view.ListView1.UpdateObject(obj);
                                            }));
                                        }
                                        catch (Exception)
                                        {
                                        }
                                    }
                                }).Start();

                                new Thread(() =>
                                {
                                    try
                                    {
                                        var Name = VendorAPI.GetVendorInfo(mac);
                                        if (Name != null)
                                        {
                                            obj.ManName = Name.data.organization_name;
                                        }
                                        else
                                        {
                                            obj.ManName = "";
                                        }
                                        view.ListView1.UpdateObject(obj);
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }).Start();

                                obj.IP           = arppacket.SenderProtocolAddress;
                                obj.MAC          = PhysicalAddress.Parse(mac.Replace(":", ""));
                                obj.DeviceName   = "Resolving";
                                obj.ManName      = "Getting information...";
                                obj.DeviceStatus = "Online";
                                view.ListView1.AddObject(obj);
                            }));
                        }
                        int percentageprogress = (int)((float)stopwatch.ElapsedMilliseconds / scanduration * 100);

                        view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = "Scanning " + percentageprogress + "%"));
                    }
                    stopwatch.Stop();
                    Main.operationinprogress = false;
                    view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = clientlist.Count.ToString() + " device(s) found"));
                    capturedevice.Close();
                    capturedevice = null;
                    BackgroundScanStart(view, interfacefriendlyname); //start passive monitoring
                }
                catch (Exception)
                {
                    try
                    {
                        view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = "Error occurred"));
                    }
                    catch (Exception)
                    {
                    }
                }
            }).Start();
            #endregion
        }
コード例 #16
0
 /// <summary>
 /// stop capturing ntwork packets
 /// </summary>
 public void StopCapturing()
 {
     _currentCaptureDevice.StopCapture();
 }
コード例 #17
0
        public static void Main(string[] args)
        {
            // Print SharpPcap version
            var ver = SharpPcap.Pcap.SharpPcapVersion;

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

            // Retrieve the device list
            var devices = SharpPcap.LibPcap.LibPcapLiveDeviceList.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();
            Console.WriteLine("The following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------");
            Console.WriteLine();

            int i = 0;

            // Print out the devices
            foreach (SharpPcap.LibPcap.LibPcapLiveDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
                i++;
            }

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

            ICaptureDevice device = devices[i];

            tcpConnectionManager.OnConnectionFound += HandleTcpConnectionManagerOnConnectionFound;

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

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

            device.Open(DeviceModes.Promiscuous, readTimeoutMilliseconds);

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

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

            // start up a thread that will periodically lock and prune the collection
            var pruningThread = new Thread(DictionaryPruner);

            pruningThread.Start();

            // start up a thread that will periodically calculate and output bandwidth
            var calculationAndDisplayThread = new Thread(CalculateAndDisplay);

            calculationAndDisplayThread.Start();

            // Wait for 'Enter' from the user.
            Console.ReadLine();

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

            // stop the pruning thread and wait for it to stop
            DictionaryPrunerStop = true;
            pruningThread.Join();

            CalculateAndDisplayStop = true;
            calculationAndDisplayThread.Join();

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

            Console.WriteLine("Captured {0} packets", PacketCount);
        }
コード例 #18
0
ファイル: Form1.cs プロジェクト: RobertCall/Nets1
 private void stop_button_Click(object sender, EventArgs e)
 {
     captureDevice.StopCapture();
     captureDevice.Close();
     captureDevice = null;
 }