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

转自: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):

 

代码
1 using System;
2  using System.Collections.Generic;
3  using System.Linq;;//需要添加引用System.Core(右键项的引用添加,在.net项可以找到)
4 using System.Text;
5 using SharpPcap;//需要添加引用SharpPcap.dll和PacketDotNet.dll
6
7 namespace TestConsole
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 //显示SharpPcap版本
14 string ver = SharpPcap.Version.VersionString;
15 Console.WriteLine("SharpPcap {0}", ver);
16
17 //获取网络设备
18 LivePcapDeviceList devices = LivePcapDeviceList.Instance;
19 if (devices.Count < 1)
20 {
21 Console.WriteLine("找不到网络设备");
22 return;
23 }
24 Console.WriteLine();
25 Console.WriteLine("以下是目前本计算机上的活动网络设备:");
26 Console.WriteLine("----------------------------------------------------");
27 Console.WriteLine();
28 int i = 0;
29 foreach (LivePcapDevice dev in devices)
30 {
31 Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
32 i++;
33 }
34
35 //选择要监听的网络设备
36 Console.WriteLine();
37 Console.Write("-- 请选择一个需要监听的网络设备: ");
38 i = int.Parse(Console.ReadLine());
39 LivePcapDevice device = devices[i];
40
41 Console.Write("-- 请选择操作:监听通讯[C/c],多线程监听通讯[T/t],监听统计[F/f],发送随机数据包[S/s]? ");
42 string resp = Console.ReadLine().ToUpper();
43
44 while (!(resp.StartsWith("C") || resp.StartsWith("F") || resp.StartsWith("T") || resp.StartsWith("S")))
45 {
46 resp = Console.ReadLine().ToUpper();
47 }
48
49 try
50 {
51 if (resp.StartsWith("C") || resp.StartsWith("F") || resp.StartsWith("T"))
52 {
53 //监听过滤条件
54 string filter = "ip and tcp";
55
56 //连接设备
57 System.Threading.Thread backgroundThread = null;
58 int readTimeoutMilliseconds = 1000;
59 if (resp.StartsWith("F"))
60 {
61 device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
62 device.SetFilter(filter);
63 device.Mode = CaptureMode.Statistics; //抓包统计
64 device.OnPcapStatistics += new StatisticsModeEventHandler(device_OnPcapStatistics); //抓包统计回调事件
65 }
66 else if (resp.StartsWith("C"))
67 {
68 device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
69 device.SetFilter(filter);
70 device.Mode = CaptureMode.Packets; //抓数据包
71 showDetails = resp.EndsWith("-A"); //当抓数据包时,检查是否要查看详情
72 device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); //抓数据包回调事件
73 }
74 else
75 {
76 backgroundThread = new System.Threading.Thread(BackgroundThread);
77 backgroundThread.Start();
78 device.Open();
79 device.SetFilter(filter);
80 device.Mode = CaptureMode.Packets; //抓数据包
81 showDetails = resp.EndsWith("-A"); //当抓数据包时,检查是否要查看详情
82 device.OnPacketArrival += new PacketArrivalEventHandler(device_OnThreadPacketArrival); //抓数据包回调事件
83 }
84
85 Console.WriteLine();
86 Console.WriteLine("-- 当前TCPdump过滤条件: \"{0}\"", filter);
87 Console.WriteLine("-- 正在监听设备 {0}, 按 '回车' 键以停止监听...", device.Description);
88
89 //开始监听
90 device.StartCapture();
91
92 //停止监听
93 Console.ReadLine();
94 device.StopCapture();
95 Console.WriteLine("-- 停止监听.");
96
97 if (backgroundThread != null)
98 {
99 BackgroundThreadStop = true;
100 backgroundThread.Join();
101 }
102 }
103 else if (resp.StartsWith("S"))
104 {
105 //连接设备
106 device.Open();
107
108 //生成随机数据包
109 byte[] bytes = GetRandomPacket();
110
111 try
112 {
113 //发送数据
114
115 device.SendPacket(bytes);
116 SendQueue squeue = new SendQueue(2000);
117 Console.WriteLine("-- 单个数据包发送成功.");
118
119 for (int j = 0; j < 10; j++)
120 {
121 if (!squeue.Add(bytes))
122 {
123 Console.WriteLine("-- 警告: 队列大小不足以存放所有数据包,将只发送部分数据包.");
124 break;
125 }
126 }
127 device.SendQueue(squeue, SendQueueTransmitModes.Synchronized);
128 Console.WriteLine("-- 数据包队列发送完毕.");
129 }
130 catch (Exception e)
131 {
132 Console.WriteLine("-- " + e.Message);
133 }
134 }
135 }
136 catch (Exception e)
137 {
138 Console.WriteLine("-- " + e.Message);
139 }
140 finally
141 {
142 if (device.Opened)
143 {
144 //断开设备连接
145 Console.WriteLine(device.Statistics().ToString());
146 device.Close();
147 Console.WriteLine("-- 断开设备连接.");
148 Console.Write("按 '回车' 键以退出...");
149 Console.Read();
150 }
151 }
152 }
153

 

posted @ 2010-11-05 17:22  armyao  阅读(4192)  评论(1编辑  收藏  举报