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来解析数据包

效果图下:

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

SharpPcap核心代码:

         /// <summary>
/// 开始捕捉
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStart_Click(object sender, EventArgs e)
{
if (this.combDevice.SelectedIndex > -)
{
StartCapture(this.combDevice.SelectedIndex);
this.btnStart.Enabled = false;
this.btnStop.Enabled = true;
}
else {
MessageBox.Show(this,"请选择一个设备","提示",MessageBoxButtons.OK);
}
} /// <summary>
/// 停止捕捉
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStop_Click(object sender, EventArgs e)
{
Shutdown();
this.btnStop.Enabled = false;
this.btnStart.Enabled = true;
} private void StartCapture(int itemIndex)
{
packetCount = ;
device = CaptureDeviceList.Instance[itemIndex];
packetStrings = new Queue<PacketWrapper>();
bs = new BindingSource();
dgvData.DataSource = bs;
LastStatisticsOutput = DateTime.Now; // start the background thread
backgroundThreadStop = false;
backgroundThread = new Thread(BackgroundThread);
backgroundThread.Start(); // setup background capture
device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
device.OnCaptureStopped += new CaptureStoppedEventHandler(device_OnCaptureStopped);
device.Open(); // tcpdump filter to capture only TCP/IP packets
string filter = "ip and tcp";
device.Filter = filter; // force an initial statistics update
captureStatistics = device.Statistics;
UpdateCaptureStatistics(); // start the background capture
device.StartCapture(); btnStop.Enabled = true;
} /// <summary>
/// 设备接收事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void device_OnPacketArrival(object sender, CaptureEventArgs e)
{
// print out periodic statistics about this device
var Now = DateTime.Now;
var interval = Now - LastStatisticsOutput;
if (interval > new TimeSpan(, , ))
{
Console.WriteLine("device_OnPacketArrival: " + e.Device.Statistics);
captureStatistics = e.Device.Statistics;
statisticsUiNeedsUpdate = true;
LastStatisticsOutput = Now;
} lock (QueueLock)
{
PacketQueue.Add(e.Packet);
}
} /// <summary>
/// 设备停止事件
/// </summary>
/// <param name="sender"></param>
/// <param name="status"></param>
private void device_OnCaptureStopped(object sender, CaptureStoppedEventStatus status)
{
if (status != CaptureStoppedEventStatus.CompletedWithoutError)
{
MessageBox.Show("Error stopping capture", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} private void UpdateCaptureStatistics()
{
tlblStatistic.Text = string.Format("接收包: {0}, 丢弃包: {1}, 接口丢弃包: {2}", captureStatistics.ReceivedPackets,captureStatistics.DroppedPackets, captureStatistics.InterfaceDroppedPackets);
}

关于SharpPcap手册

源码下载

上一篇:VMware NAT模式下设置网络


下一篇:201521123117 《Java程序设计》第6周学习总结