转自: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.dll

namespace TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            //显示SharpPcap版本
            string ver = SharpPcap.Version.VersionString;
            Console.WriteLine("SharpPcap {0}", ver);

            //获取网络设备
            LivePcapDeviceList devices = LivePcapDeviceList.Instance;
            )
            {
                Console.WriteLine("找不到网络设备");
                return;
            }
            Console.WriteLine();
            Console.WriteLine("以下是目前本计算机上的活动网络设备:");
            Console.WriteLine("----------------------------------------------------");
            Console.WriteLine();
            ;
            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;
                    ;
                    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 = );
                        Console.WriteLine("-- 单个数据包发送成功.");

                        ; j < ; 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();
                }
            }
        }

最新文章

  1. 解决Trauncate table没权限
  2. 使用亚马逊的Route53服务
  3. MapReduce应用案例--单表关联
  4. ubuntu 14.04 与 CentOS 升级GCC/G++至5版本
  5. UVa 10837 A Research Problem 欧拉函数
  6. java_final
  7. 深入理解 Javascript 面向对象编程(转)
  8. asp.net 网站所有请求跳转到同一个页面
  9. VS2012 安装出错 :通道正在关闭
  10. jQuery插件——多级联动菜单
  11. 最近学习java时的记录
  12. 基于FPGA的有限状态机浅析
  13. R+openNLP︱openNLP的六大可实现功能及其在R语言中的应用
  14. python学习之路网络编程篇(第四篇)
  15. Jetty - 教程
  16. PL_SQL学习
  17. windows server 2003产生的 Minidmp蓝屏文件分析求助
  18. mysql 架构~mgr具体细节分析
  19. (原)pycharm中debugger时console如何打开
  20. suse 关于使用 /etc/init.d/boot.local的问题

热门文章

  1. 自定义加载loading view动画组件的使用。
  2. xcode8打包ipa文件, application loader上传成功,但是iTunes Connect不显示构建版本
  3. android 内存溢出与内存泄露
  4. 阴影 box-shadow
  5. sublime text2 bracketHighLighter 配置
  6. 基于Windows 10平台的PM2.5检测器制作
  7. AjaxHelper简介
  8. ORA-01502: index ‘index_name&#39; or partition of such index is in unusable state
  9. js输出二维数组最长的子数组
  10. Consul Windows 安装