• C# 利用SharpPcap实现网络包捕获嗅探


    本文是利用SharpPcap实现网络包的捕获的小例子,实现了端口监控,数据包捕获等功能,主要用于学习分享。

    什么是SharpPcap?

    SharpPcap 是一个.NET 环境下的网络包捕获框架,基于著名的 pcap/WinPcap 库开发。提供了捕获、注入、分析和构建的功能,适用于 C# 和 VB NET 开发语言。

    SharpPcap有两部分组成:1> SharpPcap.dll 负责数据的捕获  2> PacketDotNet.dll负责数据包的解析

    思路:

    1. 通过进程名字获取对应的端口号。
    2. SharpPcap获取对应的数据包,通过解析数据包过滤相关的端口。

    涉及知识点:

    • Process 获取相关进程信息。
    • netstat命令:netstat -ano|find "3844" 获取进程对应的端口
    • SharpPcap相关信息:
      • 通过CaptureDeviceList的静态方法获取设备列表。
      • 通过OnPacketArrival事件接收数据包。
      • 通过PacketDotNet来解析数据包

    效果图下:

    SharpPcap核心代码:

      1         /// <summary>
      2         /// 开始捕捉
      3         /// </summary>
      4         /// <param name="sender"></param>
      5         /// <param name="e"></param>
      6         private void btnStart_Click(object sender, EventArgs e)
      7         {
      8             if (this.combDevice.SelectedIndex > -1)
      9             {
     10                 StartCapture(this.combDevice.SelectedIndex);
     11                 this.btnStart.Enabled = false;
     12                 this.btnStop.Enabled = true;
     13             }
     14             else {
     15                 MessageBox.Show(this,"请选择一个设备","提示",MessageBoxButtons.OK);
     16             }
     17         }
     18 
     19         /// <summary>
     20         /// 停止捕捉
     21         /// </summary>
     22         /// <param name="sender"></param>
     23         /// <param name="e"></param>
     24         private void btnStop_Click(object sender, EventArgs e)
     25         {
     26             Shutdown();
     27             this.btnStop.Enabled = false;
     28             this.btnStart.Enabled = true;
     29         }
     30 
     31         private void StartCapture(int itemIndex)
     32         {
     33             packetCount = 0;
     34             device = CaptureDeviceList.Instance[itemIndex];
     35             packetStrings = new Queue<PacketWrapper>();
     36             bs = new BindingSource();
     37             dgvData.DataSource = bs;
     38             LastStatisticsOutput = DateTime.Now;
     39 
     40             // start the background thread
     41             backgroundThreadStop = false;
     42             backgroundThread = new Thread(BackgroundThread);
     43             backgroundThread.Start();
     44 
     45             
     46             // setup background capture
     47             device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
     48             device.OnCaptureStopped +=  new CaptureStoppedEventHandler(device_OnCaptureStopped);
     49             device.Open();
     50 
     51             // tcpdump filter to capture only TCP/IP packets
     52             string filter = "ip and tcp";
     53             device.Filter = filter;
     54 
     55             // force an initial statistics update
     56             captureStatistics = device.Statistics;
     57             UpdateCaptureStatistics();
     58 
     59             // start the background capture
     60             device.StartCapture();
     61 
     62             btnStop.Enabled = true;
     63         }
     64 
     65         /// <summary>
     66         /// 设备接收事件
     67         /// </summary>
     68         /// <param name="sender"></param>
     69         /// <param name="e"></param>
     70         private void device_OnPacketArrival(object sender, CaptureEventArgs e)
     71         {
     72             // print out periodic statistics about this device
     73             var Now = DateTime.Now;
     74             var interval = Now - LastStatisticsOutput;
     75             if (interval > new TimeSpan(0, 0, 2))
     76             {
     77                 Console.WriteLine("device_OnPacketArrival: " + e.Device.Statistics);
     78                 captureStatistics = e.Device.Statistics;
     79                 statisticsUiNeedsUpdate = true;
     80                 LastStatisticsOutput = Now;
     81             }
     82             
     83             lock (QueueLock)
     84             {
     85                 PacketQueue.Add(e.Packet);
     86             }
     87         }
     88 
     89         /// <summary>
     90         /// 设备停止事件
     91         /// </summary>
     92         /// <param name="sender"></param>
     93         /// <param name="status"></param>
     94         private void device_OnCaptureStopped(object sender, CaptureStoppedEventStatus status)
     95         {
     96             if (status != CaptureStoppedEventStatus.CompletedWithoutError)
     97             {
     98                 MessageBox.Show("Error stopping capture", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     99             }
    100         }
    101 
    102         private void UpdateCaptureStatistics()
    103         {
    104             tlblStatistic.Text = string.Format("接收包: {0}, 丢弃包: {1}, 接口丢弃包: {2}", captureStatistics.ReceivedPackets,captureStatistics.DroppedPackets, captureStatistics.InterfaceDroppedPackets);
    105         }
    View Code


    关于SharpPcap手册

    源码下载

  • 相关阅读:
    软件开发中的程序员和产品经理
    Linux下自动备份MySQL
    使用FeignClient,消费方使用方法,和一些坑
    FeignClient 使用
    关于sql查询,按时间段查询
    aquery验证
    Ajax
    弹框
    来源于网络 感觉很好就收藏;了
    org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
  • 原文地址:https://www.cnblogs.com/hsiang/p/7696347.html
Copyright © 2020-2023  润新知