SharpPcap 3.4 사용 사례

16358 단어 sha
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using SharpPcap;





namespace TestConsole

{

    class Program

    {

        static void Main(string[] args)

        {

            //  SharpPcap  

            string ver = SharpPcap.Version.VersionString;

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



            //      

            var devices = LivePcapDeviceList.Instance;

            if (devices.Count < 1)

            {

                Console.WriteLine("       ");

                return;

            }



            Console.WriteLine();

            Console.WriteLine("                 :");

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

            Console.WriteLine();



            int i = 0;

            foreach (LivePcapDevice dev in devices)

            {

                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);

                i++;

            }



            //          



            Console.WriteLine();

            Console.Write("--               : ");

            i = int.Parse(Console.ReadLine());

            LivePcapDevice device = devices[i];







            Console.Write("--      :    [C/c],       [T/t],    [F/f],       [S/s]? ");

            string resp = Console.ReadLine().ToUpper();



            while (!(resp.StartsWith("C") || resp.StartsWith("F") || resp.StartsWith("T") || resp.StartsWith("S")))

            {

                resp = Console.ReadLine().ToUpper();

            }



            try

            {

                if (resp.StartsWith("C") || resp.StartsWith("F") || resp.StartsWith("T"))

                {

                    //      

                    //string filter = "ip and tcp";



                    //    

                    System.Threading.Thread backgroundThread = null;

                    

                    int readTimeoutMilliseconds = 1000;

                    if (resp.StartsWith("F"))

                    {

                        device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

                        //device.SetFilter(filter);

                        device.Mode = CaptureMode.Statistics; //    

                        device.OnPcapStatistics += new StatisticsModeEventHandler(device_OnPcapStatistics); //        



                    }



                    else if (resp.StartsWith("C"))

                    {

                        device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

                        //device.SetFilter(filter);

                        device.Mode = CaptureMode.Packets; //    

                        showDetails = resp.EndsWith("-A"); //      ,         



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



                    }



                    else

                    {

                        backgroundThread = new System.Threading.Thread(BackgroundThread);

                        backgroundThread.Start();

                        device.Open();

                       // device.SetFilter(filter);

                        device.Mode = CaptureMode.Packets; //    

                        showDetails = resp.EndsWith("-A"); //      ,         

                        device.OnPacketArrival += new PacketArrivalEventHandler(device_OnThreadPacketArrival); //        

                    }







                    Console.WriteLine();

                    //Console.WriteLine("--   TCPdump    : \"{0}\"", filter);

                    Console.WriteLine("--        {0},   '  '       ...", device.Description);





                    //    

                    device.StartCapture();



                    //    

                    Console.ReadLine();

                    device.StopCapture();

                    Console.WriteLine("--     .");

                    if (backgroundThread != null)

                    {

                        BackgroundThreadStop = true;

                        backgroundThread.Join();

                    }

                }

                else if (resp.StartsWith("S"))

                {

                    //    

                    device.Open();

                    //       

                    byte[] bytes = GetRandomPacket();

                    try

                    {



                        //    

                        device.SendPacket(bytes);

                        SendQueue squeue = new SendQueue(2000);

                        Console.WriteLine("--          .");



                        for (int j = 0; j < 10; j++)

                        {

                            if (!squeue.Add(bytes))

                            {

                                Console.WriteLine("--   :               ,         .");

                                break;

                            }

                        }

                        device.SendQueue(squeue, SendQueueTransmitModes.Synchronized);

                        Console.WriteLine("--          .");

                    }



                    catch (Exception e)

                    {

                        Console.WriteLine("-- " + e.Message);

                    }



                }



            }

            catch (Exception e)

            {

                Console.WriteLine("-- " + e.Message);

            }



            finally

            {

                if (device.Opened)

                {



                    //      



                    Console.WriteLine(device.Statistics().ToString());



                    device.Close();



                    Console.WriteLine("--       .");



                    Console.Write("  '  '     ...");



                    Console.Read();



                }



            }



        }







        static bool showDetails = false; //       



        /// <summary>



        ///     



        /// </summary>



        private static void device_OnPacketArrival(object sender, CaptureEventArgs e)

        {



            PcapPorcessContext(e.Packet);



        }







        private static void PcapPorcessContext(PacketDotNet.RawPacket pPacket)

        {



            var time = pPacket.Timeval.Date;

            var len = pPacket.Data.Length;

            var layer = pPacket.LinkLayerType;

            Console.WriteLine("{0}:{1}:{2},{3} Len={4} Layer={5}",

                    time.Hour, time.Minute, time.Second, time.Millisecond, len, layer);





            var packet = PacketDotNet.Packet.ParsePacket(pPacket); //Raw     

            if (layer == PacketDotNet.LinkLayers.Ethernet) //    

            {

                var ethernetPacket = (PacketDotNet.EthernetPacket)packet;

                System.Net.NetworkInformation.PhysicalAddress srcMac = ethernetPacket.SourceHwAddress;

                System.Net.NetworkInformation.PhysicalAddress destMac = ethernetPacket.DestinationHwAddress;

                Console.WriteLine("MAC:{0} -> {1}", srcMac, destMac);

                if (showDetails) Console.WriteLine("Ethernet packet: " + ethernetPacket.ToColoredString(false));

            }



            var ipPacket = PacketDotNet.IpPacket.GetEncapsulated(packet);  //IP 

            if (ipPacket != null)

            {

                System.Net.IPAddress srcIp = ipPacket.SourceAddress;

                System.Net.IPAddress destIp = ipPacket.DestinationAddress;

                Console.WriteLine("IP: {0} -> {1}", srcIp, destIp);

                if (showDetails) Console.WriteLine("IP packet: " + ipPacket.ToColoredString(false));

                var tcpPacket = PacketDotNet.TcpPacket.GetEncapsulated(packet); //TCP 

                if (tcpPacket != null)

                {

                    int srcPort = tcpPacket.SourcePort;

                    int destPort = tcpPacket.DestinationPort;

                    Console.WriteLine("TCP Port: {0} -> {1}", srcPort, destPort);

                    if (showDetails) Console.WriteLine("TCP packet: " + tcpPacket.ToColoredString(false));

                }

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

                if (udpPacket != null)

                {

                    int srcPort = udpPacket.SourcePort;

                    int destPort = udpPacket.DestinationPort;

                    Console.WriteLine("UDP Port: {0} -> {1}", srcPort, destPort);

                    if (showDetails) Console.WriteLine("UDP packet: " + udpPacket.ToColoredString(false));

                }

            }



        }



        static ulong oldSec = 0;

        static ulong oldUsec = 0;



        /// <summary>

        ///       

        /// </summary>

        private static void device_OnPcapStatistics(object sender, StatisticsModeEventArgs e)

        {



            //         

            ulong delay = (e.Statistics.Timeval.Seconds - oldSec) * 1000000 - oldUsec + e.Statistics.Timeval.MicroSeconds;



            //    Bits per second

            ulong bps = ((ulong)e.Statistics.RecievedBytes * 8 * 1000000) / delay;

            /*                                       ^       ^



                                                     |       |



                                                     |       | 



                                                     |       |



                            converts bytes in bits --        |



                                                             |



                        delay is expressed in microseconds --



            */







            //    Packets per second

            ulong pps = ((ulong)e.Statistics.RecievedPackets * 1000000) / delay;



            //            

            var ts = e.Statistics.Timeval.Date.ToLongTimeString();







            //       

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







            //         ,             



            oldSec = e.Statistics.Timeval.Seconds;



            oldUsec = e.Statistics.Timeval.MicroSeconds;



        }





        /// <summary>



        ///        200      



        /// </summary>

        private static byte[] GetRandomPacket()

        {



            byte[] packet = new byte[200];



            Random rand = new Random();



            rand.NextBytes(packet);



            return packet;



        }



        /// <summary>



        ///        98    



        /// </summary>

        private static byte[] GetPacket()

        {



            byte[] packet = new byte[]



            {



                0x00,0x02,0x65,0x11,0xa6,0x05,                     //srcMac



                0x00,0x1b,0x38,0xa5,0xc2,0x40,                     //destMac



                0x08,0x00,                                         //Type Ip



                0x45,                                              //Version 4



                0x00,                                              //Differentiated Services Field    



                0x00,0x54,                                         //Total Length 84



                0x43,0x08,                                         //Identification    



                0x40,0x00,                                         //Fragment offset    



                0x80,                                              //Time to live     



                0x06,                                              //Protocol TCP



                0x40,0x00,                                         //Header checksum      



                0xc0,0xa8,0x00,0x71,                               //srcIP



                0xc0,0xa8,0x00,0x6a,                               //destIP



                0x26,0x8e,                                         //srcPort



                0x04,0x04,                                         //destPort



                0x5b,0x0c,0x5e,0xc7,                               //Sequence number   



                0xca,0xf9,0x1b,0xb1,                               //Acknowledgement number    



                0x80,                                              //Header Length 32



                0x18,                                              //Flags [PSH,ACK]



                0x41,0x10,                                         //Window size



                0x82,0x72,                                         //Checksum    



                0x01,                                              //Options NOP



                0x01,                                              //Options NOP



                0x08,0x0a,0x00,0x00,0xac,0x4c,0x00,0x41,0x50,0xaa, //Options Timestamps



                0x21,                                              //Data Start                            



                0x0a,                                              //Command



                0x00,0x00,                                         //CID



                0x01,0x00,0x00,0x00,                               //TID



                0x00,0x00,0x00,0x00,                               //Param1



                0x00,0x00,0x00,0x00,                               //Param2



                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,           //Param3



                0x30,0x30,0x30,0x30,                               //ErrorCode



                0x00,0x00,0xec,0x00                                //ExtraData



            };



            return packet;



        }



        private static DateTime LastStatisticsOutput = DateTime.Now;

        private static TimeSpan LastStatisticsInterval = new TimeSpan(0, 0, 2);

        private static void device_OnThreadPacketArrival(object sender, CaptureEventArgs e)

        {



            //          



            var Now = DateTime.Now;



            var interval = Now - LastStatisticsOutput;



            if (interval > LastStatisticsInterval)

            {



                Console.WriteLine("Device Statistics: " + ((LivePcapDevice)e.Device).Statistics());



                LastStatisticsOutput = Now;



            }







            lock (QueueLock)

            {



                PacketQueue.Add(e.Packet); //              



            }



        }



        /// <summary>



        ///           



        /// </summary>

        private static void BackgroundThread()

        {



            while (!BackgroundThreadStop)

            {



                bool shouldSleep = true;







                lock (QueueLock)

                {



                    if (PacketQueue.Count != 0)

                    {



                        shouldSleep = false;



                    }



                }







                if (shouldSleep)

                {



                    System.Threading.Thread.Sleep(250);



                }



                else //    

                {



                    List<PacketDotNet.RawPacket> ourQueue; //        



                    lock (QueueLock)

                    {



                        ourQueue = PacketQueue;



                        PacketQueue = new List<PacketDotNet.RawPacket>();



                    }







                    Console.WriteLine("BackgroundThread: Local Queue Count is {0}", ourQueue.Count);







                    foreach (var packet in ourQueue)

                    {



                        PcapPorcessContext(packet);



                    }



                }



            }



        }

        private static bool BackgroundThreadStop = false; //      

        private static object QueueLock = new object(); //     

        private static List<PacketDotNet.RawPacket> PacketQueue = new List<PacketDotNet.RawPacket>(); //        





    }



}


좋은 웹페이지 즐겨찾기