Ejemplo n.º 1
0
        public static void Main(string[] args)
        {
            string verWinPCap = null;
            int    count      = 0;

            verWinPCap = Tamir
                         .IPLib
                         .Version
                         .GetVersionString();
            PcapDeviceList getNetConnections = SharpPcap.GetAllDevices();

            Console.WriteLine("WinPCap Version: {0}", verWinPCap);
            Console.WriteLine("Connected devices:\r\n");
            foreach (PcapDevice net in getNetConnections)
            {
                Console.WriteLine("{0}) {1}", count, net.PcapDescription);
                Console.WriteLine("\tName:\t{0}", net.PcapName);
                Console.WriteLine("\tMode:\t\t\t{0}", net.PcapMode);
                Console.WriteLine("\tIP Address: \t\t{0}", net.PcapIpAddress);
                Console.WriteLine("\tLoopback: \t\t{0}", net.PcapLoopback);
                Console.WriteLine();
                count++;
            }
            Console.Write("Press any <RETURN> to exit");
            Console.Read();
        }
Ejemplo n.º 2
0
 public void OnWhisper(ChatMessagePacket packet, SharpPcap.PcapCaptureEventArgs e)
 {
     if (Regex.Match(packet.Text, "spoofcheck").Success)
     {
         Keys[] keys = {
             Keys.Divide,
             Keys.R,
             Keys.Space,
             Keys.S,
             Keys.P,
             Keys.O,
             Keys.O,
             Keys.F,
             Keys.C,
             Keys.H,
             Keys.E,
             Keys.C,
             Keys.K
         };
         foreach(Keys key in keys){
             diHook.SendKey(key);
         }
         Thread.Sleep(100);
         diHook.SendKey(Keys.Enter);
     }
 }
Ejemplo n.º 3
0
        public void ReadPcapFile(string capFile)
        {
            PcapDevice device;

            try
            {
                //Get an offline file pcap device
                device = SharpPcap.GetPcapOfflineDevice(capFile);
                //Open the device for capturing
                device.PcapOpen();
            }
            catch (Exception)
            {
                return;
            }

            //Register our handler function to the 'packet arrival' event
            device.PcapOnPacketArrival +=
                new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);

            //device.PcapSetFilter(this.tcpDumpFilter);

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

            //Close the pcap device
            device.PcapClose();
        }
Ejemplo n.º 4
0
        public void ProcessPcap()
        {
            sharpPcapDict = new Dictionary <Connection, TcpRecon>();
            PcapDevice device;

            try
            {
                device = SharpPcap.GetPcapOfflineDevice(capFile);
                device.PcapOpen();
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error Loading pcap with SharpPcap: " + ex.Message;
                return;
            }

            device.PcapOnPacketArrival += new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);
            device.PcapCapture(SharpPcap.INFINITE); //parse entire pcap until EOF
            device.PcapClose();

            foreach (TcpRecon tr in sharpPcapDict.Values)
            {
                tr.isComplete = true;
                if (tr.LastSavedOffset != tr.CurrentOffset)
                {
                    AddNewNode(tr);
                }
                tr.Close();
            }

            sharpPcapDict.Clear();
            owner.Invoke(Complete, ips);

            return;
        }
Ejemplo n.º 5
0
        public static void Main3(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, ArpTest.cs", ver);
            Console.WriteLine();

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                i++;
            }

            Console.WriteLine();
            Console.Write("-- Please choose a device for sending the ARP request: ");
            i = int.Parse(Console.ReadLine());

            string device = devices[i].PcapName;

            String ip = "";

            while (true)
            {
                Console.Write("-- Please enter IP address to be resolved by ARP: ");
                ip = Console.ReadLine();
                if (IPUtil.IsIP(ip))
                {
                    break;
                }
                Console.WriteLine("Bad IP address format, please try again");
            }

            //Create a new ARP resolver
            //(for more info, see:
            //http://www.tamirgal.com/home/SourceView.aspx?Item=SharpPcap&File=ARP.cs)
            ARP arper = new ARP(device);

            //print the resolved address
            Console.WriteLine(ip + " is at: " + arper.Resolve(ip));
        }
Ejemplo n.º 6
0
 static void dev_OnPacketArrival(object sender, SharpPcap.CaptureEventArgs e)
 {
     var time = e.Packet.Timeval.Date;
     var len = e.Packet.Data.Length;
     Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
         time.Hour, time.Minute, time.Second, time.Millisecond, len);
     Console.WriteLine(e.Packet.ToString());
 }
Ejemplo n.º 7
0
        private void Start()
        {
            PcapDeviceList _PcapDeviceList = SharpPcap.GetAllDevices();
            PcapDevice     _PcapDevice     = _PcapDeviceList[0];

            _PcapDevice.PcapOnPacketArrival += new SharpPcap.PacketArrivalEvent(_PcapDevice_PcapOnPacketArrival);
            _PcapDevice.PcapOpen(false);
            _PcapDevice.PcapSetFilter("tcp and ip");
            _PcapDevice.PcapCapture(-1);
        }
Ejemplo n.º 8
0
 public void OnJoin(ChatMessagePacket packet, SharpPcap.PcapCaptureEventArgs e)
 {
     if (packet.Text.ToLower() == "clan thr")
     {
         inTHRChannel = true;
     }
     else
     {
         inTHRChannel = false;
     }
 }
Ejemplo n.º 9
0
        private void Form1_Load2(object sender, System.EventArgs e)
        {
            //Run();
            devices = SharpPcap.GetAllDevices();
            foreach (PcapDevice device in devices)
            {
                device.PcapOpen();
            }
            Thread th = new Thread(new ThreadStart(Run));

            th.Start();
        }
Ejemplo n.º 10
0
        private void device_OnPacketArrival(object sender, SharpPcap.CaptureEventArgs e)
        {
            if (e.Packet.LinkLayerType == PacketDotNet.LinkLayers.Ethernet)
            {
                PacketDotNet.Packet packet;

                long TotalPacketSize = e.Packet.Data.Length;
                BytesRead += TotalPacketSize;
                ++PacketsSeen;

                if ((PacketsSeen > 0) && ((PacketsSeen % 10000) == 0))
                {
                    DebugLog.ConsoleWindow.SelectedIndex = DebugLog.ConsoleWindow.Items.Count - 1;
                    int Progress = (int)((float)BytesRead / (float)CaptureFileSize * 100);
                    ProgressBar.Value = Progress;

                    Application.DoEvents();
                }

                try
                {
                    packet = PacketDotNet.Packet.ParsePacket(e.Packet);
                }
                catch
                {
                    return;
                }

                var ethernetPacket = (PacketDotNet.EthernetPacket)packet;

                var udpPacket = PacketDotNet.UdpPacket.GetEncapsulated(packet);

                if (udpPacket != null)
                {
                    var ipPacket = (PacketDotNet.IpPacket)udpPacket.ParentPacket;
                    System.Net.IPAddress srcIp = ipPacket.SourceAddress;
                    System.Net.IPAddress dstIp = ipPacket.DestinationAddress;

                    byte[] Payload = udpPacket.PayloadData;

                    Int32 l = udpPacket.Length - udpPacket.Header.GetLength(0);

                    if (l > 0)
                    {
                        Array.Resize(ref Payload, l);

                        StreamProcessor.ProcessPacket(srcIp, dstIp, udpPacket.SourcePort, udpPacket.DestinationPort, Payload, packet.Timeval.Date);
                    }
                }
            }
        }
Ejemplo n.º 11
0
 public void OnEmote(ChatMessagePacket packet, SharpPcap.PcapCaptureEventArgs e)
 {
     if (packet.Username == "throneit.com")
     {
         List<string> games = new List<string>();
         MatchCollection matches = Regex.Matches(packet.Text, "(thr-[a-z]*[0-9]*)");
         foreach (Match match in matches)
         {
             games.Add(match.Captures[0].Value);
             Console.WriteLine(match.Captures[0].Value);
         }
         Console.WriteLine("------------------------------------");
     }
 }
Ejemplo n.º 12
0
        private void PacketCapture_Load(object sender, EventArgs e)
        {
            try
            {
                this.promiscuousCheckbox.Enabled = true;
                this.DumpToFileCheckbox.Enabled  = true;
                this.StopCaptureButton.Enabled   = false;
                this.AmberPicture.Visible        = true;
                this.GreenPicture.Visible        = false;
                this.RedPicture.Visible          = false;
                this.updater     = this.UpdateUI;
                this.stopUpdater = this.PcapStopped;
                this.devices     = SharpPcap.GetAllDevices();
                foreach (PcapDevice device in this.devices)
                {
                    this.comboBox1.Items.Add(device.PcapDescription);
                }
                if (this.devices.Count > 0)
                {
                    this.comboBox1.SelectedIndex = 1;
                }
                this.webBrowser1.DocumentStream = new MemoryStream(Encoding.Default.GetBytes(Resources.Filtering));
            }
            catch (Exception exc)
            {
                this.Enabled = false;
                if (exc is BadImageFormatException)
                {
                    Logging.Info(
                        "Terminals Packet Capture is not configured to work with this system (Bad Image Format Exception)",
                        exc);
                    MessageBox.Show(
                        "Terminals Packet Capture is not configured to work with this system (Bad Image Format Exception)");
                }
                else if (exc is DllNotFoundException)
                {
                    Logging.Info("WinpPcap was not installed", exc);
                    ExternalLinks.ShowWinPCapPage();
                }
                else
                {
                    Logging.Info("WinpPcap was not installed correctly", exc);
                }
            }

            this.PacketCapture_Resize(null, null);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Reconstruct a Pcap file using TcpRecon class
        /// </summary>
        /// <param name="capFile"></param>
        public static void ReconSingleFileSharpPcap(string capFile)
        {
            PcapDevice device;

            //FileInfo fi = new FileInfo(capFile);
            var fi = zFile.CreateFileInfo(capFile);

            path = fi.DirectoryName + "\\";
            try
            {
                //Get an offline file pcap device
                device = SharpPcap.GetPcapOfflineDevice(capFile);
                //Open the device for capturing
                device.PcapOpen();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            //Register our handler function to the 'packet arrival' event
            device.PcapOnPacketArrival +=
                new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);

            // FOR THIS LINE TO WORK YOU NEED TO CHANGE THE
            // SHARPPCAP LIBRARY MANUALLY AND REMOVE PcapSetFilter method
            // FROM PcapOfflineDevice
            //
            // add a filter so we get only tcp packets
            // device.PcapSetFilter("tcp");

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

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

            // Clean up
            foreach (TcpRecon tr in sharpPcapDict.Values)
            {
                tr.Close();
            }
            sharpPcapDict.Clear();
        }
Ejemplo n.º 14
0
        public static void Main(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example8.ReadFile.cs", ver);
            Console.WriteLine();

            Console.WriteLine();
            Console.Write("-- Please enter an input capture file name: ");
            string capFile = Console.ReadLine();

            PcapDevice device;

            try
            {
                //Get an offline file pcap device
                device = SharpPcap.GetPcapOfflineDevice(capFile);
                //Open the device for capturing
                device.PcapOpen();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            //Register our handler function to the 'packet arrival' event
            device.PcapOnPacketArrival +=
                new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);

            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.PcapCapture(SharpPcap.INFINITE);

            //Close the pcap device
            device.PcapClose();
            Console.WriteLine("-- End of file reached.");
            Console.Write("Hit 'Enter' to exit...");
            Console.ReadLine();
        }
Ejemplo n.º 15
0
        public static void Run(string[] args)
        {
            string S    = "Hello";
            int    lLen = EthernetFields_Fields.ETH_HEADER_LEN;
            //bytes = System.Convert.ToByte(S);
            const int MIN_PKT_LEN = 42;

            byte[] data  = System.Text.Encoding.ASCII.GetBytes("HELLO");
            byte[] bytes = new byte[MIN_PKT_LEN + data.Length];
            Array.Copy(data, 0, bytes, MIN_PKT_LEN, data.Length);

            PcapDeviceList devices = SharpPcap.GetAllDevices();
            PcapDevice     device  = devices[2];
            NetworkDevice  netdev  = (NetworkDevice)device;

            UDPPacket packet = new UDPPacket(lLen, bytes);

            //Ethernet Fields
            packet.DestinationHwAddress = "001122334455";
            packet.SourceHwAddress      = netdev.MacAddress;
            packet.EthernetProtocol     = EthernetProtocols_Fields.IP;


            //IP Fields
            packet.DestinationAddress = "58.100.187.167";

            packet.SourceAddress  = netdev.IpAddress;
            packet.IPProtocol     = IPProtocols_Fields.UDP;
            packet.TimeToLive     = 20;
            packet.Id             = 100;
            packet.Version        = 4;
            packet.IPTotalLength  = bytes.Length - lLen;
            packet.IPHeaderLength = IPFields_Fields.IP_HEADER_LEN;

            //UDP Fields
            packet.DestinationPort = 9898;
            packet.SourcePort      = 80;
            packet.ComputeIPChecksum();
            packet.ComputeUDPChecksum();

            device.PcapOpen();
            device.PcapSendPacket(packet);
            device.PcapClose();
        }
Ejemplo n.º 16
0
        public static void Main(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example4.IfList.cs", ver);

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                Console.WriteLine();
                /* Name */
                Console.WriteLine("\tName:\t{0}", dev.PcapName);
                /* IP Address */
                Console.WriteLine("\tIP Address: \t\t{0}", dev.PcapIpAddress);
                /* Is Loopback */
                Console.WriteLine("\tLoopback: \t\t{0}", dev.PcapLoopback);

                Console.WriteLine();
                i++;
            }
            Console.Write("Hit 'Enter' to exit...");
            Console.ReadLine();
        }
Ejemplo n.º 17
0
 private void PacketCapture_Load(object sender, EventArgs e)
 {
     try {
         promiscuousCheckbox.Enabled = true;
         DumpToFileCheckbox.Enabled  = true;
         StopCaptureButton.Enabled   = false;
         AmberPicture.Visible        = true;
         GreenPicture.Visible        = false;
         RedPicture.Visible          = false;
         updater     = new MethodInvoker(UpdateUI);
         stopUpdater = new MethodInvoker(PcapStopped);
         devices     = SharpPcap.GetAllDevices();
         foreach (PcapDevice device in devices)
         {
             comboBox1.Items.Add(device.PcapDescription);
         }
         if (devices.Count > 0)
         {
             comboBox1.SelectedIndex = 1;
         }
         this.webBrowser1.DocumentStream = new System.IO.MemoryStream(System.Text.ASCIIEncoding.Default.GetBytes(Terminals.Properties.Resources.Filtering));
     } catch (Exception exc) {
         this.Enabled = false;
         if (exc is System.BadImageFormatException)
         {
             Terminals.Logging.Log.Debug("Terminals Packet Capture is not configured to work with this system (Bad Image Format Exception)", exc);
             System.Windows.Forms.MessageBox.Show("Terminals Packet Capture is not configured to work with this system (Bad Image Format Exception)");
         }
         else if (exc is System.DllNotFoundException)
         {
             Terminals.Logging.Log.Debug("WinpPcap was not installed", exc);
             if (System.Windows.Forms.MessageBox.Show("It appears that WinPcap is not installed.  In order to use this feature within Terminals you must first install that product.  Do you wish to visit the download location right now?", "Download WinPcap?", MessageBoxButtons.OKCancel) == DialogResult.OK)
             {
                 System.Diagnostics.Process.Start("http://www.winpcap.org/install/default.htm");
             }
         }
         else
         {
             Terminals.Logging.Log.Debug("WinpPcap was not installed correctly", exc);
         }
     }
     this.PacketCapture_Resize(null, null);
 }
Ejemplo n.º 18
0
 public DevicesForm()
 {
     InitializeComponent();
     try
     {
         this.deviceList = SharpPcap.GetAllDevices();
         foreach (PcapDevice pd in deviceList)
         {
             this.comboBoxDevices.Items.Add(pd.PcapDescription);
         }
         this.comboBoxDevices.SelectedIndex = 0;
     }
     catch (DllNotFoundException)
     {
         MessageBox.Show("It seem's you haven't installed WinPcap.\n"
                         + "You can get it from http://www.winpcap.org .", "Missing DLL", MessageBoxButtons.OK, MessageBoxIcon.Error);
         Environment.Exit(1);
     }
 }
Ejemplo n.º 19
0
 private void startCapture()
 {
     while (IsCapturing)
     {
         if (_device == null)
         {
             if (_offlineDevs.Count > 0)
             {
                 DeviceName = _offlineDevs[0];
                 _device    = SharpPcap.GetPcapOfflineDevice(DeviceName);
                 _offlineDevs.RemoveAt(0);
             }
             else
             {
                 StopCapture();
             }
         }
         else
         {
             DeviceName = ((NetworkDevice)_device).Description;
         }
         try
         {
             _device.PcapOpen();
         }
         catch (Exception ee)
         {
             ErrorMsg = ee.Message;
             StopCapture();
             return;
         }
         //Register our handler function to the
         //'packet arrival' event
         _device.PcapOnPacketArrival += new SharpPcap.PacketArrivalEvent(pcapOnPacketArrival);
         //Start the capturing process
         _device.PcapCapture(SharpPcap.INFINITE);
         //Close the pcap device
         _device.PcapClose();
         _device = null;
     }
 }
Ejemplo n.º 20
0
        private void Initialize()
        {
            try
            {
                // Try to find a Networkinterface
                this.deviceList = SharpPcap.GetAllDevices();
            }
            catch (DllNotFoundException)
            {
                MessageBox.Show("Es sieht so aus das du kein WinPcap installiert hast. besorg es dir von hier: http://www.winpcap.org", "Fehlende DLL-Datei", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
            catch (Exception e)
            {
#if DEBUG
                Program.debugStream.WriteLine(e.Message);
                Program.debugStream.WriteLine(e.StackTrace);
                Program.debugStream.WriteLine(e.Source);
#endif
            }

            if (this.deviceList.Count < 1)
            {
                MessageBox.Show("Keine Netzwerk Schnittstellen gefunden =(");
                return;
            }
            try
            {
                this.beep = new SoundPlayer(Environment.CurrentDirectory + "\\data\\ok.wav");
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show(Environment.CurrentDirectory + "\\data\\ok.wav nicht gefunden");
            }
            if (!OptionsForm.Instance.MuteSounds)
            {
                this.beep.Play();
            }

            this.startSniffers();
        }
Ejemplo n.º 21
0
        public static void Main1(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, SendTcpSynExample.cs", ver);
            Console.WriteLine();

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                i++;
            }

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

            PcapDevice device = devices[i];

            SendTcpSyn((NetworkDevice)device);
        }
Ejemplo n.º 22
0
        private static void readFile()
        {
            string capFile
                = @"C:\test2.pcap";//Console.ReadLine();

            PcapDevice device;

            try
            {
                //Get an offline file pcap device
                device = SharpPcap.GetPcapOfflineDevice(capFile);
                //Open the device for capturing
                device.PcapOpen();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            //Register our handler function to the 'packet arrival' event
            device.PcapOnPacketArrival +=
                new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);


            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.PcapCapture(SharpPcap.INFINITE);

            //Close the pcap device
            device.PcapClose();
            Console.WriteLine("-- End of file reached.");
            Console.In.ReadLine();
        }
Ejemplo n.º 23
0
        public packet(SharpPcap.RawCapture pPacket)
        {
            var timestamp = pPacket.Timeval.Date;
            this.layer = pPacket.LinkLayerType;
            this.time = timestamp.Hour.ToString() + ":" + timestamp.Minute.ToString() + ":" + timestamp.Second.ToString() + "," + timestamp.Millisecond.ToString();
            this.srcIp = "";
            this.destIp = "";
            this.protocol = "";
            this.info = "";
            this.color = "White";

            this.pPacket = pPacket;
            this.rPacket = PacketDotNet.Packet.ParsePacket(pPacket.LinkLayerType, pPacket.Data);

            this.frame_info = new Dictionary<string, string>();
            this.ethernet_info = new Dictionary<string, string>();

            this.ip_info = new Dictionary<string, string>();
            this.arp_info = new Dictionary<string, string>();

            this.icmp_info = new Dictionary<string, string>();
            this.igmp_info = new Dictionary<string, string>();
            this.tcp_info = new Dictionary<string, string>();
            this.udp_info = new Dictionary<string, string>();

            this.application_info = new Dictionary<string, string>();
            this.application_byte = null;

            analysis_packet();

            // 计算校验和
            if (this.tcp_info.Count > 0 && this.tcp_info["Checksum(校验和)"] != this.tcp_info["tcpPacket计算校验和函数计算结果"])
            {
                this.color = "Red";
            }
        }
Ejemplo n.º 24
0
 public PcapDeviceList GetInterfaces()
 {
     /* Retrieve the device list */
     return(SharpPcap.GetAllDevices());
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Statistics would be a great way of detecting DoS attacks - more efficient than looking at individual packet detection
 /// </summary>
 /// <param name="statsPacket"></param>
 /// <param name="lasTimeval"></param>
 /// <param name="sensorId"></param>
 public void ReportStatistics(SharpPcap.WinPcap.StatisticsModePacket statsPacket, SharpPcap.PosixTimeval lasTimeval, string sensorId)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 26
0
        public static void Main(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example11.Statistics.cs", ver);

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                i++;
            }

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

            PcapDevice device = devices[i];

            //Register our handler function to the 'pcap statistics' event
            device.PcapOnPcapStatistics +=
                new Tamir.IPLib.SharpPcap.PcapStatisticsEvent(device_PcapOnPcapStatistics);

            //Open the device for capturing
            //true -- means promiscuous mode
            //1000 -- means stats will be collected 1000ms
            device.PcapOpen(true, 1000);

            //Handle TCP packets only
            device.PcapSetFilter("tcp");

            //Set device to statistics mode
            device.PcapMode = PcapMode.Statistics;

            Console.WriteLine();
            Console.WriteLine("-- Gathering statistics on \"{0}\", hit 'Enter' to stop...",
                              device.PcapDescription);

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

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

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

            //Close the pcap device
            device.PcapClose();
            Console.WriteLine("Capture stopped, device closed.");
            Console.Write("Hit 'Enter' to exit...");
            Console.ReadLine();
        }
Ejemplo n.º 27
0
 private IPAddress getIPAddressForAdpater(SharpPcap.LibPcap.LibPcapLiveDevice pdev)
 {
     IPAddress ip;
     foreach (SharpPcap.LibPcap.PcapAddress pcap_ip in pdev.Addresses)
     {
         ip = pcap_ip.Addr.ipAddress;
         if (ip != null)
             if (ip.AddressFamily != AddressFamily.InterNetworkV6)
                 return ip;
     }
     return null;
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Dumps each received packet to a pcap file
        /// </summary>
        private static void device_PcapOnPacketArrival(object sender, SharpPcap.CaptureEventArgs e)
        {
            ICaptureDevice device = (ICaptureDevice)sender;
            //if device has a dump file opened
            if (device.DumpOpened)
            {
                device.Dump(e.Packet);
            }

            _packetCount++;
        }
Ejemplo n.º 29
0
        public static void Main(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example4.IfListAdv.cs", ver);

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                Console.WriteLine();
                /* Name */
                Console.WriteLine("\tName:\t\t{0}", dev.PcapName);
                /* Is Loopback */
                Console.WriteLine("\tLoopback:\t\t{0}", dev.PcapLoopback);

                /*
                 *      If the device is a physical network device,
                 *      lets print some advanced info
                 */
                if (dev is NetworkDevice)
                {                //Then..
                    /* Cast to NetworkDevice */
                    NetworkDevice netDev = (NetworkDevice)dev;
                    /* Print advanced info */
                    Console.WriteLine("\tIP Address:\t\t{0}", netDev.IpAddress);
                    Console.WriteLine("\tSubnet Mask:\t\t{0}", netDev.SubnetMask);
                    Console.WriteLine("\tMAC Address:\t\t{0}", netDev.MacAddress);
                    Console.WriteLine("\tDefault Gateway:\t{0}", netDev.DefaultGateway);
                    Console.WriteLine("\tPrimary WINS:\t\t{0}", netDev.WinsServerPrimary);
                    Console.WriteLine("\tSecondary WINS:\t\t{0}", netDev.WinsServerSecondary);
                    Console.WriteLine("\tDHCP Enabled:\t\t{0}", netDev.DhcpEnabled);
                    Console.WriteLine("\tDHCP Server:\t\t{0}", netDev.DhcpServer);
                    Console.WriteLine("\tDHCP Lease Obtained:\t{0}", netDev.DhcpLeaseObtained);
                    Console.WriteLine("\tDHCP Lease Expires:\t{0}", netDev.DhcpLeaseExpires);
                    Console.WriteLine("\tAdmin Status:\t{0}", netDev.AdminStatus);
                    Console.WriteLine("\tMedia State:\t{0}", netDev.MediaState);
                }
                Console.WriteLine();
                i++;
            }
            Console.Write("Hit 'Enter' to exit...");
            Console.ReadLine();
        }
Ejemplo n.º 30
0
        public static void Main(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example10.SendQueues.cs", ver);

            Console.WriteLine();
            Console.Write("-- Please enter an input capture file name: ");
            string capFile = Console.ReadLine();

            PcapDevice device;

            try
            {
                //Get an offline file pcap device
                device = SharpPcap.GetPcapOfflineDevice(capFile);
                //Open the device for capturing
                device.PcapOpen();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            Console.Write("Queueing packets...");

            //Allocate a new send queue
            PcapSendQueue squeue = new PcapSendQueue
                                       ((int)((PcapOfflineDevice)device).PcapFileSize);
            Packet packet;

            try
            {
                //Go through all packets in the file and add to the queue
                while ((packet = device.PcapGetNextPacket()) != null)
                {
                    if (!squeue.Add(packet))
                    {
                        Console.WriteLine("Warning: packet buffer too small, " +
                                          "not all the packets will be sent.");
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            Console.WriteLine("OK");

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

            int i = 0;

            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                i++;
            }

            Console.WriteLine();
            Console.Write("-- Please choose a device to transmit on: ");
            i = int.Parse(Console.ReadLine());
            devices[i].PcapOpen();
            string resp;

            if (devices[i].PcapDataLink != device.PcapDataLink)
            {
                Console.Write("Warning: the datalink of the capture" +
                              " differs from the one of the selected interface, continue? [YES|no]");
                resp = Console.ReadLine().ToLower();

                if ((resp != "") && (!resp.StartsWith("y")))
                {
                    Console.WriteLine("Cancelled by user!");
                    devices[i].PcapClose();
                    return;
                }
            }
            device.PcapClose();
            device = devices[i];

            Console.Write("This will transmit all queued packets through" +
                          " this device, continue? [YES|no]");
            resp = Console.ReadLine().ToLower();

            if ((resp != "") && (!resp.StartsWith("y")))
            {
                Console.WriteLine("Cancelled by user!");
                return;
            }

            try
            {
                Console.Write("Sending packets...");
                int sent = device.PcapSendQueue(squeue, true);
                Console.WriteLine("Done!");
                if (sent < squeue.CurrentLength)
                {
                    Console.WriteLine("An error occurred sending the packets: {0}. " +
                                      "Only {1} bytes were sent\n", device.PcapLastError, sent);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
            //Free the queue
            squeue.Dispose();
            Console.WriteLine("-- Queue is disposed.");
            //Close the pcap device
            device.PcapClose();
            Console.WriteLine("-- Device closed.");
            Console.Write("Hit 'Enter' to exit...");
            Console.ReadLine();
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Gets a pcap stat object and calculate bps and pps
        /// </summary>
        private static void device_OnPcapStatistics(object sender, SharpPcap.WinPcap.StatisticsModeEventArgs e)
        {
            // Calculate the delay in microseconds from the last sample.
            // This value is obtained from the timestamp that's associated with the sample.
            ulong delay = (e.Statistics.Timeval.Seconds - oldSec) * 1000000 - oldUsec + e.Statistics.Timeval.MicroSeconds;

            // Get the number of Bits per second
            ulong bps = ((ulong)e.Statistics.RecievedBytes * 8 * 1000000) / delay;
            /*                                       ^       ^
                                                     |       |
                                                     |       | 
                                                     |       |
                            converts bytes in bits --        |
                                                             |
                        delay is expressed in microseconds --
            */

            // Get the number of Packets per second
            ulong pps = ((ulong)e.Statistics.RecievedPackets * 1000000) / delay;

            // Convert the timestamp to readable format
            var ts = e.Statistics.Timeval.Date.ToLongTimeString();

            // Print Statistics
            Console.WriteLine("{0}: bps={1}, pps={2}", ts, bps, pps); 

            //store current timestamp
            oldSec = e.Statistics.Timeval.Seconds;
            oldUsec = e.Statistics.Timeval.MicroSeconds;
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Dumps each received packet to a pcap file
        /// </summary>
        private static void device_PcapOnPacketArrival(object sender, SharpPcap.CaptureEventArgs e)
        {
            SyslogMessage msg = null;

            try
            {
                Packet link =  Packet.ParsePacket(LinkLayers.Ethernet, e.Packet.Data);
                EthernetPacket ethernet = (EthernetPacket)link;
                IpPacket ip = (IpPacket)ethernet.PayloadPacket;
                UdpPacket udp = (UdpPacket)ip.PayloadPacket;
                msg = new SyslogMessage(udp);
                outputFile.WriteLine(System.Text.Encoding.ASCII.GetString(udp.PayloadData));
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("SwsyslogService", ex.ToString(), EventLogEntryType.Error);
            }

            // if the output file is ready to write, write the log file ...
            if (msg != null && outputFile.BaseStream.CanWrite)
            {
                //outputFile.WriteLine(msg.ToString());
            }

            _logEntryCount++;
        }
Ejemplo n.º 33
0
        private void OnPacketArrival(object sender, SharpPcap.CaptureEventArgs e)
        {
            var rawPacket = e.Packet;
            var etherPacket = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data);
            var ipPacket = (IpPacket)etherPacket.PayloadPacket;
            var tcpPacket = (TcpPacket)etherPacket.PayloadPacket.PayloadPacket;
            var payload = etherPacket.PayloadPacket.PayloadPacket.PayloadData;
            var toServer = tcpPacket.DestinationPort == 20100;

            if (payload.Length < 1)
                return;

            if (toServer && _srcPort == 0)
            {
                _srcPort = tcpPacket.SourcePort;
                _srcIP = ipPacket.SourceAddress;
                _destIP = ipPacket.DestinationAddress;
                var ether = (EthernetPacket)etherPacket;

                _destPhysical = ether.DestinationHwAddress;
                _srcPhsyical = ether.SourceHwAddress;
            }

            if (toServer && !put)
            {
                put = true;
                Console.WriteLine(etherPacket);
            }
            Gunz2Packet packet = new Gunz2Packet(payload, _cryptKey);
            if (packet.pktID == 0xC1C)
            {
                Array.Clear(_cryptKey, 0, _cryptKey.Length);
                var index = 33;
                var cryptKeySeed = BitConverter.ToUInt32(packet.data, index);

                MakeCryptKey(cryptKeySeed);
                var writer = new StreamWriter("gunz2shark.log", true);
                writer.WriteLine("[KEY]");
                Program.PacketLog(_cryptKey, 0, _cryptKey.Length, writer);
                writer.WriteLine("[END KEY]\n");
                writer.Close();
            }

            if (packet.pktID == 0xDFC)
            {
                SendSupplyBoxOpen();
            }

            var cmd = _commands.Find(x => x.GetOpcode() == packet.pktID);

            if (cmd != null && !packet.flags.unkFlag3)
            {

                File.WriteAllBytes(cmd.GetOpcode() + ".bin", packet.data);
                var writer = new StreamWriter("gunz2shark.log", true);

                var output = string.Format("[{0}] | {1} | {2}({2:X}) | Parameters ->", toServer ? "C2S" : "S2C", cmd.Desc, cmd.GetOpcode());

                if (cmd.Params != null)
                {
                    foreach (var param in cmd.Params)
                        output += string.Format("{0} -> ", param.Type);
                }

                output += "end";

                Console.WriteLine(output);
                writer.WriteLine(output);

                Program.PacketLog(packet.data, 0, (int)packet.data.Length, writer);
                writer.Close();
            }
            else
                Console.WriteLine("Unknown command: {0}", packet.pktID);
        }
Ejemplo n.º 34
0
        public static void Main(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example3.BasicCap.cs", ver);

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                i++;
            }

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

            PcapDevice device = devices[i];

            //Register our handler function to the 'packet arrival' event
            device.PcapOnPacketArrival +=
                new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);

            //Open the device for capturing
            //true -- means promiscuous mode
            //1000 -- means a read wait of 1000ms
            device.PcapOpen(true, 1000);

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

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

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

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

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

            //Close the pcap device
            device.PcapClose();
        }
Ejemplo n.º 35
0
        private void PcapPorcessContext(SharpPcap.RawCapture pPacket)
        {
            packet temp = new packet(pPacket);
            packets.Add(temp);

            if (this.dataGridView1.InvokeRequired)
            {
                //if (temp.ip_info.Count > 0 && temp.ip_info["Version(版本)"] == "IPv6" && temp.tcp_info.Count > 0)
                //if (temp.ip_info.Count > 0 && temp.ip_info["Version(版本)"] == "IPv4" && temp.ip_info["Protocol(协议)"] == "IGMP")
                filterCheckDelegate filterDelegate = filter_check;
                IAsyncResult asyncResult = filterDelegate.BeginInvoke(temp, null, null);
                bool flag = filterDelegate.EndInvoke(asyncResult);
                if (flag)
                {
                    this.dataGridView1.BeginInvoke(new setDataGridViewDelegate(setDataGridView), new object[] { temp, packets.Count - 1 });
                }
            }
            else
            {/*
                int index = this.dataGridView1.Rows.Add();
                this.dataGridView1.Rows[index].DefaultCellStyle.BackColor = Color.FromName(temp.color);
                this.dataGridView1.Rows[index].Cells[0].Value = temp.time;
                this.dataGridView1.Rows[index].Cells[1].Value = temp.srcIp;
                this.dataGridView1.Rows[index].Cells[2].Value = temp.destIp;
                this.dataGridView1.Rows[index].Cells[3].Value = temp.protocol;
                this.dataGridView1.Rows[index].Cells[4].Value = temp.info;
                this.dataGridView1.Rows[index].Cells[5].Value = packets.Count - 1;

                this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.Rows.Count - 1;
            */}
        }
        static void Main(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example12.PacketManipulation.cs", ver);
            Console.WriteLine();

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                i++;
            }
            Console.WriteLine("{0}) {1}", i, "Read packets from offline pcap file");

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

            PcapDevice device = null;

            if (choice == i)
            {
                Console.Write("-- Please enter an input capture file name: ");
                string capFile = Console.ReadLine();
                device = SharpPcap.GetPcapOfflineDevice(capFile);
            }
            else
            {
                device = devices[choice];
            }


            //Register our handler function to the 'packet arrival' event
            device.PcapOnPacketArrival +=
                new Tamir.IPLib.SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);

            //Open the device for capturing
            //true -- means promiscuous mode
            //1000 -- means a read wait of 1000ms
            device.PcapOpen(true, 1000);

            Console.WriteLine();
            Console.WriteLine
                ("-- Listenning on {0}, hit 'Ctrl-C' to exit...",
                device.PcapDescription);

            //Start capture 'INFINTE' number of packets
            device.PcapCapture(SharpPcap.INFINITE);

            //Close the pcap device
            //(Note: this line will never be called since
            // we're capturing infinite number of packets
            device.PcapClose();
        }
Ejemplo n.º 37
0
        static void Main1(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example9.SendPacket.cs", ver);
            Console.WriteLine();

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                i++;
            }

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

            PcapDevice device = devices[i];

            Console.Write("-- This will send a random packet out this interface," +
                          "continue? [YES|no]");
            string resp = Console.ReadLine().ToLower();

            //If user refused, exit program
            if (resp == "n" || resp == "no")
            {
                return;
            }

            PcapSendQueue queue = new PcapSendQueue(10000);

            byte[] bytes;
            bytes = GetRandomPacket();
            queue.Add(GetRandomPacket(), 0, 0);
            Console.WriteLine(queue.CurrentLength);
            queue.Add(GetRandomPacket(), 0, 10);
            Console.WriteLine(queue.CurrentLength);
            queue.Add(GetRandomPacket(), 2, 0);
            Console.WriteLine(queue.CurrentLength);
            queue.Add(GetRandomPacket(), 2, 1);
            Console.WriteLine(queue.CurrentLength);

            //Open the device
            device.PcapOpen();
            Console.WriteLine(device.PcapSendQueue(queue, true));
            Console.WriteLine(device.PcapLastError);
            device.PcapClose();
            queue.Dispose();
            Console.WriteLine(" device closed");
        }
Ejemplo n.º 38
0
 static NetWorkController()
 {
     _devicelist = SharpPcap.GetAllDevices();
 }
Ejemplo n.º 39
0
        void packetArrive(object sender, SharpPcap.CaptureEventArgs packet)
        {
            PacketDotNet.Packet v = PacketDotNet.Packet.ParsePacket(packet.Packet.LinkLayerType, packet.Packet.Data);
            sPacket pp = new sPacket(ref v);
            packList.Add(pp);
            var typeStr = pp.finalType.Name;
            foreach (var i in pyDissectorList)
                if (i.Key.pass(ref v))
                {
                    HLPacket tmpPacket;
                    if (i.Value.parsePacket(v, out tmpPacket))
                    {
                        pp.finalType = typeof(HLPacket);
                        typeStr = tmpPacket.packetType;
                    }
                }

            if (_packetTypeCnt.ContainsKey(typeStr))
                _packetTypeCnt[typeStr] += 1;
            else
                _packetTypeCnt[typeStr] = 1;

            if (onlineFilter == null || onlineFilter.pass(ref v))
                onParseComplete(ref pp);
        }
Ejemplo n.º 40
0
 public void ReportStatistics(SharpPcap.WinPcap.StatisticsModePacket statsPacket, PosixTimeval lastTimeval,string sensorId)
 {
     Console.WriteLine("stats packet:\t" + statsPacket.RecievedPackets + "\t" + statsPacket.RecievedBytes + "\t" +  statsPacket.Timeval.CompareTo(lastTimeval));
 }
Ejemplo n.º 41
0
        public static void Main(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example4.BasicCapNoCallback.cs", ver);

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                i++;
            }

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

            PcapDevice device = devices[i];

            //Open the device for capturing
            //true -- means promiscuous mode
            //1000 -- means a read wait of 1000ms
            device.PcapOpen(true, 1000);

            Console.WriteLine();
            Console.WriteLine("-- Listenning on {0}...",
                              device.PcapDescription);

            Packet packet;

            //Keep capture packets using PcapGetNextPacket()
            while ((packet = device.PcapGetNextPacket()) != null)
            {
                // Prints the time and length of each received packet
                DateTime time = packet.PcapHeader.Date;
                int      len  = packet.PcapHeader.PacketLength;
                Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
                                  time.Hour, time.Minute, time.Second, time.Millisecond, len);
            }

            //Close the pcap device
            device.PcapClose();
            Console.WriteLine("-- Timeout (1000ms) elapsed, capture stopped, device closed.");
            Console.Write("Hit 'Enter' to exit...");
            Console.ReadLine();
        }
Ejemplo n.º 42
0
        public static void Main(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example6.DumpTCP.cs", ver);
            Console.WriteLine();

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                i++;
            }

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

            PcapDevice device = devices[i];

            //Register our handler function to the 'packet arrival' event
            device.PcapOnPacketArrival +=
                new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);

            //Open the device for capturing
            //true -- means promiscuous mode
            //1000 -- means a read wait of 1000ms
            device.PcapOpen(true, 1000);

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

            //Associate the filter with this capture
            device.PcapSetFilter(filter);

            Console.WriteLine();
            Console.WriteLine
                ("-- The following tcpdump filter will be applied: \"{0}\"",
                filter);
            Console.WriteLine
                ("-- Listenning on {0}, hit 'Ctrl-C' to exit...",
                device.PcapDescription);

            //Start capture 'INFINTE' number of packets
            device.PcapCapture(SharpPcap.INFINITE);

            //Close the pcap device
            //(Note: this line will never be called since
            // we're capturing infinite number of packets
            device.PcapClose();
        }
Ejemplo n.º 43
0
        public static void Main(string[] args)
        {
            string ver = Tamir.IPLib.Version.GetVersionString();

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example9.SendPacket.cs", ver);
            Console.WriteLine();

            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                i++;
            }

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

            PcapDevice device = devices[i];

            Console.Write("-- This will send a random packet out this interface, " +
                          "continue? [YES|no]");
            string resp = Console.ReadLine().ToLower();

            //If user refused, exit program
            if ((resp != "") && (!resp.StartsWith("y")))
            {
                Console.WriteLine("Cancelled by user!");
                return;
            }

            //Open the device
            device.PcapOpen();

            //Generate a random packet
            byte[] bytes = GetRandomPacket();

            try
            {
                //Send the packet out the network device
                device.PcapSendPacket(bytes);
                Console.WriteLine("-- Packet sent successfuly.");
            }
            catch (Exception e)
            {
                Console.WriteLine("-- " + e.Message);
            }

            //Close the pcap device
            device.PcapClose();
            Console.WriteLine("-- Device closed.");
            Console.Write("Hit 'Enter' to exit...");
            Console.ReadLine();
        }