SharpPcap网络包捕获框架的使用--实例代码在vs2005调试通过

来源:互联网 发布:微信群二维码采集软件 编辑:程序博客网 时间:2024/05/16 14:28
转自:http://hi.baidu.com/boyxgb/blog/item/89ac86fbdff5f82c4e4aea2e.html

由于项目的需要,要从终端与服务器的通讯数据中获取终端硬件状态,所以用到了广为流传的C#抓包库SharpPcap。
SharpPcap目前最新版本是3.1.0,基于.Net 3.5和WinPcap。这儿请注意,如果你用的版本和我的版本差别太大,就不需要浪费时间看这篇文章了。比方说你用的是基于.Net 2.0的旧版,库完全不一样,请搜索SharpPcap,旧版SharpPcap的文章还是挺多的,或者你用的是最新的版本,那请直接参考SharpPcap下载网站的最新版source包里的examples中的内容。
在使用前首先需要安装WinPcap,下载地址:http://www.winpcap.org/install/default.htm
SharpPcap下载地址:http://sourceforge.net/projects/sharppcap/,下载SharpPcap dll库包SharpPcap-3.1.0.bin.zip,同样也可以在files里找到对应的source包SharpPcap-3.1.0.src.zip和SharpPcap历史版本。
SharpPcap库下载之解压后,直接在项目中引用SharpPcap.dll和PacketDotNet.dll即可使用了。

下面贴我整理出来的SharpPcap的示例大全的代码,其实也就是把source包examples中的官方示例里我所用得上的内容整合在了一起(不包括ARP、DumpFile和MultipleFilters):

代码using System; using System.Collections.Generic; using System.Linq;;//需要添加引用System.Core(右键项的引用添加,在.net项可以找到)using System.Text;using SharpPcap;//需要添加引用SharpPcap.dll和PacketDotNet.dllnamespace TestConsole{    class Program    {        static void Main(string[] args)        {            //显示SharpPcap版本            string ver = SharpPcap.Version.VersionString;            Console.WriteLine("SharpPcap {0}", ver);            //获取网络设备            LivePcapDeviceList 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();                }            }        }

 

0 0
原创粉丝点击