小编给大家分享一下C#如何利用SharpPcap实现网络包捕获,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
网站制作、建网站找专业网站设计公司成都创新互联:定制网站、模板网站、仿站、小程序开发、软件开发、重庆App定制开发等。做网站价格咨询成都创新互联:服务完善、十余年建站、值得信赖!网站制作电话:028-86922220
什么是SharpPcap?
SharpPcap 是一个.NET 环境下的网络包捕获框架,基于著名的 pcap/WinPcap 库开发。提供了捕获、注入、分析和构建的功能,适用于 C# 和 VB NET 开发语言。
SharpPcap有两部分组成:1> SharpPcap.dll 负责数据的捕获 2> PacketDotNet.dll负责数据包的解析
思路:
通过进程名字获取对应的端口号。
SharpPcap获取对应的数据包,通过解析数据包过滤相关的端口。
涉及知识点:
Process 获取相关进程信息。
netstat命令:netstat -ano|find "3844" 获取进程对应的端口
SharpPcap相关信息:
通过CaptureDeviceList的静态方法获取设备列表。
通过OnPacketArrival事件接收数据包。
通过PacketDotNet来解析数据包
效果图下:
SharpPcap核心代码:
////// 开始捕捉 /// /// /// private void btnStart_Click(object sender, EventArgs e) { if (this.combDevice.SelectedIndex > -1) { StartCapture(this.combDevice.SelectedIndex); this.btnStart.Enabled = false; this.btnStop.Enabled = true; } else { MessageBox.Show(this,"请选择一个设备","提示",MessageBoxButtons.OK); } } ////// 停止捕捉 /// /// /// private void btnStop_Click(object sender, EventArgs e) { Shutdown(); this.btnStop.Enabled = false; this.btnStart.Enabled = true; } private void StartCapture(int itemIndex) { packetCount = 0; device = CaptureDeviceList.Instance[itemIndex]; packetStrings = new Queue(); 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; } /// /// 设备接收事件 /// /// /// 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(0, 0, 2)) { Console.WriteLine("device_OnPacketArrival: " + e.Device.Statistics); captureStatistics = e.Device.Statistics; statisticsUiNeedsUpdate = true; LastStatisticsOutput = Now; } lock (QueueLock) { PacketQueue.Add(e.Packet); } } ////// 设备停止事件 /// /// /// 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); }
看完了这篇文章,相信你对“C#如何利用SharpPcap实现网络包捕获”有了一定的了解,如果想了解更多相关知识,欢迎关注创新互联行业资讯频道,感谢各位的阅读!