c#实现网络抓包及协议分析

主界面设计(随意)

在这里插入图片描述

抓包代码


    public partial class MainWindow : Form
    {
        private CaptureDeviceList devices;        //接口列表
        public static string[] name = new string[100];      //接口名称
        public static int Selectid=-1;        //用于捕获的接口的索引
        string NowIP="";        //当前接口的IP地址
        public static DeviceMode mode;        //捕获模式
        public bool State=false;          //状态(1正在捕获,1未打开)


        private BindingSource BS=new BindingSource();        //DataGridView数据绑定
        List<ParketAnalysis> listAn = new List<ParketAnalysis>();     //分析数据包容器
        private List<ParketStatistics> listSs = new List<ParketStatistics>();       //统计数据包容器
        public static Dictionary<string, int> SendCnt = new Dictionary<string, int>();       //用于统计发送到某个IP地址包的数目
        public static Dictionary<string, int> ReceiveCnt = new Dictionary<string, int>();       //用于统计接收某个IP地址包的数目
        int No = 0;     //数据包包编号
        object Lock=new object();//线程锁

        //过滤部分
        string Filter="";      //过滤字段
        string FilterIP = "";   //过滤IP


        public MainWindow()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        //配置
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            devices = CaptureDeviceList.Instance;       //获取当前的所有网卡
            if (devices.Count < 1)
            {
                MessageBox.Show("当前没有活动的网络设备!");
                return;
            }
            //初始化接口
            Config cf = new Config(devices);
            cf.ShowDialog();
            if(Selectid==-1)
            {
                return;
            }
            else
            {
                string[] t = devices[Selectid].ToString().Split('\n');      //分割
                string[] t2 = t[13].Split(':');
                NowIP = t2[1];      //本机IP
                toolStripLabel1.Text = "准备捕获网络" + name[Selectid] + "的数据包";
            }
        }

        //启动
        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            if (Selectid == -1)
            {
                MessageBox.Show("请选择需要捕获的网络!");
                return;
            }
            else if (listAn.Count != 0)
            {
                #region 是否保存
                //弹出对话窗
                DialogResult dr1 = MessageBox.Show("重新捕获将清空现有内容,是否继续?", "提示", MessageBoxButtons.OKCancel);
                if (dr1 == DialogResult.OK)      //清空重新捕获
                {
                    //保存过程
                    Reset();        //清空
                    BtnStart.Enabled = false;
                    btnStop.Enabled = true;
                    dataGridView.DataSource = BS;
                    toolStripLabel1.Text = "正在捕获网络" + name[Selectid] + "的数据包";
                    Start_Capture(devices[Selectid]);                    //开始捕获
                }
                else             //取消
                {
                    return;
                }
                #endregion
            }
            else
            {
                Reset();        //清空
                BtnStart.Enabled = false;
                btnStop.Enabled = true;
                dataGridView.DataSource = BS;
                toolStripLabel1.Text = "正在捕获网络" + name[Selectid] + "的数据包";
                //开始捕获
                Start_Capture(devices[Selectid]);
            }
        }

        //暂停
        private void btnStop_Click(object sender, EventArgs e)
        {
            this.State = false;  //设置状态
            BtnStart.Enabled = true;
            btnStop.Enabled = false;
            toolStripLabel1.Text = "准备捕获网络" + name[Selectid] + "的数据包";
            this.Stop();        //停止捕获
        }

        //开始捕获方法
        private void Start_Capture(ICaptureDevice dev)
        {
            this.State = true;      //设置运行状态
            dev.OnPacketArrival += new PacketArrivalEventHandler(Fun_Arrival);           //注册处理包事件
            dev.Open(mode);         //开启
            dev.StartCapture();           //开始捕获(异步)
        }

        //包处理事件方法
        private void Fun_Arrival(object sender, CaptureEventArgs e)
        {
            this.BeginInvoke(new MethodInvoker(delegate
            {
                ParketStatistics temp = new ParketStatistics(No, e.Packet);         //转换为数据包统计
                lock (Lock)
                {
                    int ID = ConditonType(Filter);          //判断过滤方式
                    if (ID == 0)      //无过滤
                    {
                        BS.Add(temp);      //添加到数据绑定
                    }
                    else if(ID==1)      //协议过滤
                    {
                            for (int k = 0; k < temp.ProtocolList.Count; ++k)
                            {
                                if (temp.ProtocolList[k] == Filter)
                                    BS.Add(temp);
                            }
                        }
                    else if (ID == 2)      //源IP过滤
                    {
                        if (temp.src == FilterIP)
                            BS.Add(temp);      //添加到数据绑定
                    }
                    else if (ID == 3)      //目的IP过滤
                    {
                        if (temp.dst == FilterIP)
                            BS.Add(temp);      //添加到数据绑定
                    }
                    else if (ID == 4)      //源IP或目的IP过滤
                    {
                        if (temp.src == FilterIP|| temp.dst == FilterIP)
                            BS.Add(temp);      //添加到数据绑定
                    }
                    toolStripLabel1.Text = "正在捕获网络" + name[Selectid] + "的数据包,已捕获:"+(listSs.Count+1)+",已显示:"+BS.Count;
                    listSs.Add(temp);
                    //分析数据包 添加到容器
                    ParketAnalysis pa = new ParketAnalysis(temp);
                    listAn.Add(pa);
                    //发送到目的地址的包数目统计(发送地址为本机)
                    if (temp.src == NowIP)
                    {
                        if (SendCnt.ContainsKey(temp.dst) == false)
                            SendCnt.Add(temp.dst, 0);
                        SendCnt[temp.dst]++;
                    }
                    //本机从某个IP接收的包数目统计(接收地址为本机)
                    if (temp.dst==NowIP)
                    {
                        if (ReceiveCnt.ContainsKey(temp.src) == false)
                            ReceiveCnt.Add(temp.src, 0);
                        ReceiveCnt[temp.src]++;
                    }
                    No++;
                }
            }));
        }
      

展示

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43587354/article/details/106995501
今日推荐