c#多线程端口扫描

yitian130 2007-02-08 11:52:51
哪个朋友帮我调试一下面的代码~!谢谢~!,随便问一下,朋友有没人c#多线程方面的电子书~!我的邮箱lybyt130@163.com
我在这里先说谢谢了~!
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace 端口扫描器
{
   /// <summary>
   /// Form1 的摘要说明。
   /// </summary>
   public class MainApp : System.Windows.Forms.Form
   {
      private System.Windows.Forms.Label lblAddr;
      private System.Windows.Forms.Label label1;
      private System.Windows.Forms.Label label2;
      private System.Windows.Forms.TextBox txtAddr;
      private System.Windows.Forms.TextBox txtStart;
      private System.Windows.Forms.TextBox txtEnd;
      private System.Windows.Forms.ProgressBar progressBar1;
      private System.Windows.Forms.Button btnScan;
      private System.Windows.Forms.ListBox lbResult;
      
      //定义私有变量
      private int port;
      private string Addr;
      private bool[] done =new bool[65536];
      private int start;
      private int end;
      private Thread scanThread;
      private bool OK;
      private int i;
      private System.Windows.Forms.Label lblStart;
      private System.Windows.Forms.Label lblNow;
      private System.Windows.Forms.Label lblStop;
      private System.Windows.Forms.Label label3;
      private System.Windows.Forms.StatusBar statusBar1;
      private System.Windows.Forms.StatusBarPanel statusBarPanel2;


      /// <summary>
      /// 必需的设计器变量。
      /// </summary>
      private System.ComponentModel.Container components = null;

      public MainApp()
      {
         //
         // Windows 窗体设计器支持所必需的
         //
         InitializeComponent();

         //
         // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
         //
      }

      /// <summary>
      /// 清理所有正在使用的资源。
      /// </summary>
      protected override void Dispose( bool disposing )
      {
         if( disposing )
         {
            if (components != null)
            {
               components.Dispose();
            }
         }
         base.Dispose( disposing );
      }

      #region Windows 窗体设计器生成的代码
...全文
771 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
nine_suns99 2007-02-13
  • 打赏
  • 举报
回复
终于调试通过了
本来我向通过委托来使用线程安全的访问控件,但是似乎楼主的东东起了太多的线程,导致堆栈溢出了。

最后通过一个简单的方法解决了
就是在InitializeComponent方法中加上一句:
MainApp.CheckForIllegalCrossThreadCalls = false;
不检测从线程来的非法调用就ok了

还有一个问题就是楼主对每一个端口都起了一个线程去扫描,这样速度肯定没有单线程的快,因为线程之间的切换还需要时间

解决办法就是添加一个线程数的输入框
主线程在启动扫描子线程的时候只启动相应线程数的扫描子线程

每个子线程开始扫描端口依次递加,步长为线程数

线程0扫描端口 start + 0 ,start + threadNum + 0 ,…… ,到end结束
线程1扫描端口 start + 1 ,start + threadNum + 1 ,…… ,到end结束
线程2扫描端口 start + 2 ,start + threadNum + 2 ,…… ,到end结束
线程3扫描端口 start + 3 ,start + threadNum + 3 ,…… ,到end结束
……
线程threadNum扫描端口 start + threadNum , start + threadNum + threadNum , …… ,到end结束

这样的话就没问题了

楼主如果还有什么问题我们继续讨论
yitian130 2007-02-13
  • 打赏
  • 举报
回复
谢谢~!朋友~!^-^
jxf654 2007-02-12
  • 打赏
  • 举报
回复
up
yitian130 2007-02-11
  • 打赏
  • 举报
回复
等待答案,分不够可以加~!
yitian130 2007-02-11
  • 打赏
  • 举报
回复
兄弟~!
yitian130 2007-02-11
  • 打赏
  • 举报
回复
呵呵~!谢谢楼上~!再帮我看看,我自己调试了几次,还是不知道怎么回事,是不是,要用monitor,控制资源
nine_suns99 2007-02-11
  • 打赏
  • 举报
回复
发现一个问题:

收回刚才说的问题1,楼主是起了一个线程之后在这个线程中起多个线程

呵呵
nine_suns99 2007-02-11
  • 打赏
  • 举报
回复
暂时发现了2个问题:

1.不是多线程扫描,而是单线程的

现象描述:btnScan_Click()方法中是启动了一个新线程来完成扫描

解决方法:在btnScan_Click()方法中通过循环启动多个线程,每个线程扫描一段端口号

2.C#中的控件不允许不是创建他的线程访问,所以你的结果输出不到textBox中

现象描述:PortScan()方法中向类属性lbResult中添加结果

解决办法:通过2个类来实现所有功能,窗体类只负责显示,线程类只负责扫描,将窗体类的实例作为构造方法的参数传给线程类,窗体类提供添加结果的方法,线程类扫描出结果后调用窗体类实例的添加结果方法让窗体类显示。

再调试调试,调通了再继续发
yitian130 2007-02-08
  • 打赏
  • 举报
回复
/// <summary>
      /// 应用程序的主入口点。
      /// </summary>
      [STAThread]
      static void Main()
      {
         Application.Run(new MainApp());
      }
      #region 处理扫描事件=========================================
      private void btnScan_Click(object sender, System.EventArgs e)
      {
         if (txtAddr.Text.Trim()=="")
         {
            MessageBox.Show("提示:请输入您要扫描的主机地址!","信息");
            txtAddr.Focus();
            return;
         }
         else if (txtStart.Text.Trim()=="")

         {
            MessageBox.Show("提示:请输入您要扫描的开始端口!","信息");
            txtStart.Focus();
            return;
         }
         else if(txtEnd.Text.Trim()=="")
         {
            MessageBox.Show("提示:请输入您要扫描的结束端口!","信息");
            txtEnd.Focus();
            return;
         }
         else
         {
            lbResult.Items.Clear();
            lbResult.Items.Add("端口扫描器 v1.0");
            lbResult.Items.Add("");
            lbResult.Items .Add("正在连接主机 ...");
            IPHostEntry serverHe;
            try
            {
               
               serverHe=Dns.GetHostByName(txtAddr.Text);
            }
            catch(Exception)
            {
               lbResult.Items .Add("连接主机失败 ...");
               return;
            }

         }

         Thread process=new Thread(new ThreadStart(PortScan));
         process.Start();
         progressBar1.Minimum=Int32.Parse(txtStart.Text);
         progressBar1.Maximum =Int32.Parse(txtEnd.Text);


      }
      #endregion
      #region 扫描过程=============================================
      private void PortScan()
      {
         start=Int32.Parse(txtStart.Text);
         end =Int32.Parse(txtEnd.Text);
         if ((start>=0 && start<=65536) && (end>=0 && end<=65536))
         
         {   
            lbResult.Items .Add("开始扫描..(可能需要请您等待几分钟)");
            lbResult.Items .Add("--------------------------------------------");
            Addr=txtAddr.Text;
            for (int i=start;i<=end;i++)
            {
               port=i;
               scanThread=new Thread(new ThreadStart(Scan));
               scanThread.Start();
               System.Threading.Thread.Sleep(100);
               progressBar1.Value =i;
               lblNow.Text =i.ToString();
            }
            while(!OK)
            {
               OK=true;
               for (int i=start;i<=end;i++)
               {
                  if (!done[i])
                  {
                     OK=false;
                     break;
                  }
               }
               System.Threading.Thread.Sleep(1000);

            }
            lbResult.Items .Add("--------------------------------------------");
            lbResult.Items.Add("扫描结束!");
            
            DialogResult answer;
            answer = MessageBox.Show("你要保存扫描报告吗?","信息",MessageBoxButtons.YesNo,MessageBoxIcon.Information);
            if(answer == DialogResult.Yes)
            {
               string fname = ".\\"+txtAddr.Text+".txt";
               FileInfo finfo = new FileInfo(fname);

               //判断文件是否存在
               
               if ( finfo.Exists)
               {
                  //删除该文件
                  finfo.Delete();
               }

               
               for (int i=0;i<=lbResult.Items.Count-1;i++)
               {   
                  WriteRportFile(lbResult.Items[i].ToString());
               }      
               MessageBox.Show("扫描报告保存完成,在程序目录下!","信息");
            }      

         }
         else
         {
            MessageBox.Show("可用的端口范围为[0-65536]","提示");
         }
      }


      private void Scan()
      {
         int portnow=port;
         done[portnow]=true;
         TcpClient objTCP=null;
         try
         {
            objTCP=new TcpClient(Addr,portnow);
            lbResult.Items.Add("端口 "+portnow.ToString()+ " 开放!");
         }
         catch
         {}
   
      }

      private void txtStart_TextChanged(object sender, System.EventArgs e)
      {
         lblStart.Text=txtStart.Text;
      }

      private void txtEnd_TextChanged(object sender, System.EventArgs e)
      {
         lblStop.Text=txtEnd.Text;
      }
      #endregion
      #region 校验端口输入=========================================
      private void txtStart_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
      {
         if("0123456789".IndexOf(e.KeyChar) == -1 && e.KeyChar !=(char)8)
         {
            e.Handled = true ;
         }
      }

      private void txtEnd_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
      {
         if("0123456789".IndexOf(e.KeyChar) == -1 && e.KeyChar !=(char)8)
         {
            e.Handled = true ;
         }
      }
      #endregion
      #region 将扫描报告写入文件文件===============================
      public void WriteRportFile(String input)
      {   
         //指定日志文件的目录
         string fname = ".\\"+txtAddr.Text+".txt";
         //定义文件信息对象
         FileInfo finfo = new FileInfo(fname);
         
         //创建只写文件流
         using(FileStream fs = finfo.OpenWrite())
         {
            //根据上面创建的文件流创建写数据流
            StreamWriter w = new StreamWriter(fs);
            //设置写数据流的起始位置为文件流的末尾
            w.BaseStream.Seek(0, SeekOrigin.End);
            //写入... ”
            w.Write(input+"\r\n");
            w.Flush();
            //关闭写数据流
            w.Close();
         }
      }

      #endregion

   }
}
yitian130 2007-02-08
  • 打赏
  • 举报
回复
//
         // label3
         //
         this.label3.AutoSize = true;
         this.label3.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
         this.label3.ForeColor = System.Drawing.Color.Red;
         this.label3.Location = new System.Drawing.Point(16, 288);
         this.label3.Name = "label3";
         this.label3.Size = new System.Drawing.Size(178, 17);
         this.label3.TabIndex = 12;
         this.label3.Text = "注:可用的端口范围为[0-65536]";
         //
         // statusBar1
         //
         this.statusBar1.Location = new System.Drawing.Point(0, 309);
         this.statusBar1.Name = "statusBar1";
         this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
                                                                   this.statusBarPanel2});
         this.statusBar1.ShowPanels = true;
         this.statusBar1.Size = new System.Drawing.Size(518, 22);
         this.statusBar1.TabIndex = 13;
         //
         // statusBarPanel2
         //
         this.statusBarPanel2.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
         this.statusBarPanel2.Text = "没有版权,任意复制! 设计:Super QQ:9066818 网址:http://www.wosft.net";
         this.statusBarPanel2.Width = 550;
         //
         // MainApp
         //
         this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
         this.ClientSize = new System.Drawing.Size(518, 331);
         this.Controls.Add(this.statusBar1);
         this.Controls.Add(this.label3);
         this.Controls.Add(this.lblStop);
         this.Controls.Add(this.lblNow);
         this.Controls.Add(this.lblStart);
         this.Controls.Add(this.lbResult);
         this.Controls.Add(this.btnScan);
         this.Controls.Add(this.progressBar1);
         this.Controls.Add(this.txtEnd);
         this.Controls.Add(this.txtStart);
         this.Controls.Add(this.txtAddr);
         this.Controls.Add(this.label2);
         this.Controls.Add(this.label1);
         this.Controls.Add(this.lblAddr);
         this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
         this.MaximizeBox = false;
         this.Name = "MainApp";
         this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
         this.Text = "端口扫描器 V1.0";
         ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).EndInit();
         this.ResumeLayout(false);

      }
      #endregion
yitian130 2007-02-08
  • 打赏
  • 举报
回复
/// <summary>
      /// 设计器支持所需的方法 - 不要使用代码编辑器修改
      /// 此方法的内容。
      /// </summary>
      private void InitializeComponent()
      {
         this.lblAddr = new System.Windows.Forms.Label();
         this.label1 = new System.Windows.Forms.Label();
         this.label2 = new System.Windows.Forms.Label();
         this.txtAddr = new System.Windows.Forms.TextBox();
         this.txtStart = new System.Windows.Forms.TextBox();
         this.txtEnd = new System.Windows.Forms.TextBox();
         this.progressBar1 = new System.Windows.Forms.ProgressBar();
         this.btnScan = new System.Windows.Forms.Button();
         this.lbResult = new System.Windows.Forms.ListBox();
         this.lblStart = new System.Windows.Forms.Label();
         this.lblNow = new System.Windows.Forms.Label();
         this.lblStop = new System.Windows.Forms.Label();
         this.label3 = new System.Windows.Forms.Label();
         this.statusBar1 = new System.Windows.Forms.StatusBar();
         this.statusBarPanel2 = new System.Windows.Forms.StatusBarPanel();
         ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).BeginInit();
         this.SuspendLayout();
         //
         // lblAddr
         //
         this.lblAddr.AutoSize = true;
         this.lblAddr.Location = new System.Drawing.Point(24, 24);
         this.lblAddr.Name = "lblAddr";
         this.lblAddr.Size = new System.Drawing.Size(54, 17);
         this.lblAddr.TabIndex = 0;
         this.lblAddr.Text = "主机地址";
         //
         // label1
         //
         this.label1.AutoSize = true;
         this.label1.Location = new System.Drawing.Point(24, 50);
         this.label1.Name = "label1";
         this.label1.Size = new System.Drawing.Size(54, 17);
         this.label1.TabIndex = 1;
         this.label1.Text = "开始端口";
         //
         // label2
         //
         this.label2.AutoSize = true;
         this.label2.Location = new System.Drawing.Point(24, 78);
         this.label2.Name = "label2";
         this.label2.Size = new System.Drawing.Size(54, 17);
         this.label2.TabIndex = 2;
         this.label2.Text = "结束端口";
         //
         // txtAddr
         //
         this.txtAddr.BackColor = System.Drawing.Color.PowderBlue;
         this.txtAddr.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
         this.txtAddr.Location = new System.Drawing.Point(80, 16);
         this.txtAddr.Name = "txtAddr";
         this.txtAddr.Size = new System.Drawing.Size(112, 21);
         this.txtAddr.TabIndex = 3;
         this.txtAddr.Text = "";
         //
         // txtStart
         //
         this.txtStart.BackColor = System.Drawing.Color.PowderBlue;
         this.txtStart.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
         this.txtStart.Location = new System.Drawing.Point(80, 44);
         this.txtStart.Name = "txtStart";
         this.txtStart.Size = new System.Drawing.Size(112, 21);
         this.txtStart.TabIndex = 4;
         this.txtStart.Text = "";
         this.txtStart.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtStart_KeyPress);
         this.txtStart.TextChanged += new System.EventHandler(this.txtStart_TextChanged);
         //
         // txtEnd
         //
         this.txtEnd.BackColor = System.Drawing.Color.PowderBlue;
         this.txtEnd.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
         this.txtEnd.Location = new System.Drawing.Point(80, 72);
         this.txtEnd.Name = "txtEnd";
         this.txtEnd.Size = new System.Drawing.Size(112, 21);
         this.txtEnd.TabIndex = 5;
         this.txtEnd.Text = "";
         this.txtEnd.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtEnd_KeyPress);
         this.txtEnd.TextChanged += new System.EventHandler(this.txtEnd_TextChanged);
         //
         // progressBar1
         //
         this.progressBar1.Location = new System.Drawing.Point(24, 112);
         this.progressBar1.Name = "progressBar1";
         this.progressBar1.Size = new System.Drawing.Size(168, 24);
         this.progressBar1.TabIndex = 6;
         //
         // btnScan
         //
         this.btnScan.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
         this.btnScan.Location = new System.Drawing.Point(64, 224);
         this.btnScan.Name = "btnScan";
         this.btnScan.Size = new System.Drawing.Size(80, 24);
         this.btnScan.TabIndex = 7;
         this.btnScan.Text = "扫描";
         this.btnScan.Click += new System.EventHandler(this.btnScan_Click);
         //
         // lbResult
         //
         this.lbResult.BackColor = System.Drawing.Color.PowderBlue;
         this.lbResult.ForeColor = System.Drawing.Color.Red;
         this.lbResult.ItemHeight = 12;
         this.lbResult.Location = new System.Drawing.Point(208, 0);
         this.lbResult.Name = "lbResult";
         this.lbResult.Size = new System.Drawing.Size(312, 304);
         this.lbResult.TabIndex = 8;
         //
         // lblStart
         //
         this.lblStart.Location = new System.Drawing.Point(24, 152);
         this.lblStart.Name = "lblStart";
         this.lblStart.Size = new System.Drawing.Size(48, 40);
         this.lblStart.TabIndex = 9;
         //
         // lblNow
         //
         this.lblNow.Location = new System.Drawing.Point(80, 152);
         this.lblNow.Name = "lblNow";
         this.lblNow.Size = new System.Drawing.Size(48, 40);
         this.lblNow.TabIndex = 10;
         //
         // lblStop
         //
         this.lblStop.Location = new System.Drawing.Point(136, 152);
         this.lblStop.Name = "lblStop";
         this.lblStop.Size = new System.Drawing.Size(45, 40);
         this.lblStop.TabIndex = 11;

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧