C# 异步多线程 sharpPcap 抓包

这是一个使用C#和sharpPcap库实现的网络嗅探器,用于异步多线程抓取和分析TCP/IP包。程序通过Winpcap安装,并在后台线程中运行,捕获到的数据包括各种协议(如TCP, UDP)的信息,如源和目标地址、端口等。同时,提供了统计功能,展示不同类型的包计数,以及进度条显示各协议占比。" 103714007,9154857,实现计算奇数和与判断奇偶性的函数,"['编程', '算法', '函数', '整数操作']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要在电脑上安装Winpcap 还没有写完

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using SharpPcap;
using PacketDotNet;

namespace Network_monitoring
{
    public partial class Sniffers : Form
    {

        private List<RawCapture> PacketQueue = new List<RawCapture>();
        private System.Threading.Thread backgroundThread;
        private DateTime LastStatisticsOutput;
        private TimeSpan LastStatisticsInterval = new TimeSpan(0, 0, 2);
        private CaptureDeviceList devices;
        private ICaptureDevice dev;
        private static int number = 0;
        private ICaptureStatistics captureStatistics;
        private bool statisticsUiNeedsUpdate = false;
        private PacketArrivalEventHandler arrivalEventHandler;
        private Queue<PacketWrapper> myPackets;
        private DeviceMode mode;
        System.Collections.ArrayList PacketList = new System.Collections.ArrayList();
        public int TotalCount = 0;
        public int ARPCount = 0;
        public int EthernetCount = 0;
        public int ICMPCount = 0;
        public int IGMPCount = 0;
        public int IPCount = 0;
        public int TCPCount = 0;
        public int UDPCount = 0;

        public Sniffers()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.devices = CaptureDeviceList.Instance;
            foreach (var dev in devices)
            {
                var des = dev.Description.Split('\'');
                var str = String.Format("{0}:{1}", dev.Name.ToString(), des[1]);
                this.comboBox1.Items.Add(str);
            }
            myPackets = new Queue<PacketWrapper>();
        }

        /// <summary>
        /// When true the background thread will terminate
        /// </summary>
        /// <param name="args">
        /// A <see cref="System.String"/>
        /// </param>
        private bool BackgroundThreadStop;

        /// <summary>
        /// Object that is used to prevent two threads from accessing
        /// PacketQueue at the same time
        /// </summary>
        /// <param name="args">
        /// A <see cref="System.String"/>
        /// </param>
        private object QueueLock = new object();

        /// <summary>
        /// The queue that the callback thread puts packets in. Accessed by
        /// the background thread when QueueLock is held
        /// </summary>
        

        public class PacketWrapper
        {
            public PacketDotNet.EthernetPacket ePacket;
            public string time;
            public DateTime times;
            public string timess;
            public string timesss;
            public DateTime timessss;
            public RawCapture p;
            public string protocol;
            public string len;
            public string SourAddress;
            public string DestionAddress;
            public string SourPort;
            public string DestionPort;
            public PacketWrapper(int count, RawCapture p)
            {
                var packet = PacketDotNet.EthernetPacket.ParsePacket(p.LinkLayerType, p.Data);
                this.ePacket = (PacketDotNet.EthernetPacket)packet;
                this.p = p;
                this.No = count;
                this.len = packet.Bytes.Length.ToString();
                this.times = Convert.ToDateTime("08:00:00");
                this.timesss = p.Timeval.Date.ToString();
                this.timess = timesss.Substring(Convert.ToInt32(timesss.IndexOf(" ") + 1));
                this.timessss = Convert.ToDateTime(timess);
                this.timessss = timessss.AddHours(times.Hour);
                this.time = this.timess.Replace(timess, timessss.ToString());
                this.protocol = "";
                getDetail();
            }

            public void getDetail()
            {
                var packet = Packet.ParsePacket(p.LinkLayerType, p.Data);
                this.protocol = this.ePacket.Type.ToString();
                var ipPacket = PacketDotNet.IpPacket.GetEncapsulated(packet);
                if (ipPacket != null)
                {
                    this.protocol = ipPacket.Protocol.ToString();
                    this.SourAddress = ipPacket.SourceAddress.ToString();
                    this.DestionAddress = ipPacket.DestinationAddress.ToString();
                }
                else
                {
                    this.SourAddress = "Null";
                    this.DestionAddress = "Null";
                }
                if (this.protocol == "TCP")
                {
                    PacketDotNet.TcpPacket tcppacket = TcpPacket.GetEncapsulated(packet);
                    this.SourPort = tcppacket.SourcePort.ToString();
                    this.DestionPort = tcppacket.DestinationPort.ToString();
                    if (tcppacket != null)
                    {
                        int Sport = tcppacket.SourcePort;
                        int Dport = tcppacket.DestinationPort;
                        if (Sport == 80 || Sport == 8080 || Sport == 3128)
                        {
                            this.protocol = "HTTP";
                        }
                        else if (Sport == 21)
                        {
                            this.protocol = "FTP";
                        }
                        else if (Sport == 25)
                        {
                            this.protocol = "SMTP";
                        }
                        else if (Sport == 110)
                        {
                            this.protocol = "POP3";
                        }
                    }
                }
                else if (this.protocol == "UDP")
                {
                    PacketDotNet.UdpPacket udppacket = UdpPacket.GetEncapsulated(packet);
                    this.SourPort = udppacket.SourcePort.ToString();
                    this.DestionPort = udppacket.DestinationPort.ToString();
                    if (udppacket != null)
                    {
                        int port = udppacket.SourcePort;

                        if (port == 53)
                        {
                            this.protocol = "DNS";
                        }
                    }
                }
                else if (this.protocol == "Arp")
                {
                    this.SourPort = "Null";
                    this.DestionPort = "Null";
                }
                else if (this.protocol == "ICMP")
                {
                    this.SourPort = "Null";
                    this.DestionPort = "Null";
                }
                else if (this.protocol == "IGMP")
                {
                    this.SourPort = "Null";
                    this.DestionPort = "Null";
                }
                else if (this.protocol == "Ethernet")
                {
                    this.SourPort = "Null";
                    this.DestionPort = "Null";
                }
            }

            public int No { get; private set; }
            public string Protocol { get { return protocol; } }
            public string Length { get { return len; } }
            public string SourceA { get { return SourAddress; } }
            public string Sourse { get { return ePacket.SourceHwAddress.ToString(); } }
            public string SourceP { get { return SourPort; } }
            public string DestionA { get { return DestionAddress; } }
            public string Destination { get { return ePacket.DestinationHwAddress.ToString(); } }
            public string destionP { get { return DestionPort; } }
            public string Time { get { return time; } }
            //public string Times { get { return timess; } }
        }

        /// <summary>
        /// Checks for queued packets. If any exist it locks the QueueLock, saves a
        /// reference of the current queue for itself, puts a new queue back into
        /// place into PacketQueue and unlocks QueueLock. This is a minimal amount of

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值