【问题标题】:Speed up Port Scan C#加快端口扫描 C#
【发布时间】:2012-11-25 14:00:54
【问题描述】:

我正在尝试在 C# 中创建端口扫描器,到目前为止我有这个:

private void ip()
{
    int start = 70;
    int end = 80;
    string ipString;
    if (this.comboBox1.Text == "Domain") {
         ipString= Dns.GetHostEntry(txtHost.Text).AddressList[0].ToString();
    }
    else {
        ipString = txtHost.Text;
    }
    TcpClient asd = new TcpClient();
    // MessageBox.Show(ipString);     
    IPAddress address = IPAddress.Parse(ipString);
    for (int i = start; i <= end; i++)
    {
        try
        {
            asd.SendTimeout = 3000;
            asd.ReceiveTimeout = 3000;
            asd.Connect(address, i);

            if (asd.Connected)
            {
                MessageBox.Show("Port " + i + " is open");
            }
        }
        catch
        {
            MessageBox.Show("Port " + i + " is closed");
        }
    }
}

但是对于封闭的端口,它有点慢,大约 20 秒,我应该怎么做才能使这个过程更快? 非常感谢。

【问题讨论】:

  • “有点慢”。您应该测量哪个位较慢,这样我们就不必猜测了。
  • 您应该考虑异步网络 API。有很多可供选择,但如果您重视自己的理智,请考虑 .net4.5 和 async/await api。同样值得考虑的是,没有一个 .net DNS api 有任何好处。也许可以考虑使用第 3 方选项。见:stackoverflow.com/questions/11480742/…
  • 慢,大约 20 秒。

标签: c# sockets web port-scanning


【解决方案1】:

你应该使用线程。

http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx

为您要检查的每个端口启动单独的线程,并让回调通知您哪些端口已打开,哪些未打开。

【讨论】:

  • 如何调用多参数线程?私有 void ip(strin ip, int start, int end) { } ?
  • 当你甚至不知道哪个部分“有点慢”时,你怎么能提出这个建议?添加额外线程很少是加快网络代码速度的好方法。
  • 在任何情况下都需要线程,因为无论他做什么,他的代码都会阻塞主 UI 线程。网络代码需要线程。
  • @IgorPerić 不一定,TcpClient 中也有相当强大的异步方法。
【解决方案2】:

您需要在完成测试后关闭连接。

catch 语句的末尾尝试asd.Close();

它大大加快了我的进程。

【讨论】:

    【解决方案3】:

    您应该像这样声明您的委托和异步函数(示例中的两个参数)

    public delegate void UpdateUIThreadDelegate(int par1, int par2);
    void UpdateUIThread(int par1, int par2)
    {
           ...
    }
    

    你应该这样称呼你异步函数:

    this.Invoke(new UpdateUIThreadDelegate(UpdateUIThread), new object[] { par1, par2 });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 2020-11-01
      • 2017-12-10
      • 2019-08-30
      • 2012-07-17
      • 1970-01-01
      相关资源
      最近更新 更多