0

我正在尝试在 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 秒,我应该怎么做才能让这个过程更快?非常感谢。

4

3 回答 3

1

你应该使用线程。

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

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

于 2012-11-25T14:03:25.900 回答
0

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

在你的陈述asd.Close();结束时尝试。catch

它大大加快了我的进程。

于 2013-12-08T03:03:11.617 回答
0

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

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

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

this.Invoke(new UpdateUIThreadDelegate(UpdateUIThread), new object[] { par1, par2 });
于 2012-11-25T14:13:03.237 回答