如何更快地扫描TCP端口?

时间:2012-01-26 19:53:04

标签: c# asynchronous port-scanning

我正在尝试异步扫描TCP端口。由于开放端口只需几百分之一毫秒即可完成它们很好,但是当端口关闭时我必须等待响应。

所以会发生的是我运​​行应用程序,几乎马上我看到端口80打开了。然后我必须等半分钟才能扫描所有其他端口。

EDIT。另外,我想在发生响应时显示响应,而不是等待其他端口进行检查。

如何加快速度?

private void btnStart_Click(object sender, EventArgs e)
{
    for (int port = 79; port < 90; port++)
    {
        ScanPort(port);
    }
}

private void ScanPort(int port)
{
    TcpClient client = new TcpClient();
    client.BeginConnect(IPAddress.Parse("74.125.226.84"), port, new AsyncCallback(CallBack), client);
}

private void CallBack(IAsyncResult result)
{
    bool connected = false;

    using (TcpClient client = (TcpClient)result.AsyncState)
    {
        try
        {
            client.EndConnect(result);
            connected = client.Connected;
        }
        catch (SocketException)
        {
        }
    }

    if (connected)
    {
        this.Invoke((MethodInvoker)delegate
        {
            txtDisplay.Text += "open2" + Environment.NewLine;
        });
    }
    else
    {
        this.Invoke((MethodInvoker)delegate
        {
            txtDisplay.Text += "closed2" + Environment.NewLine;
        });
    } 
}

1 个答案:

答案 0 :(得分:7)

您可以使用WaitHandle BeginConnect返回只等待这么久。

using (var tcp = new TcpClient())
{
    var ar = tcp.BeginConnect(host, port, null, null);
    using (ar.AsyncWaitHandle)
    {
        //Wait 2 seconds for connection.
        if (ar.AsyncWaitHandle.WaitOne(2000, false))
        {
            try
            {
                tcp.EndConnect(ar);
                //Connect was successful.
            }
            catch
            {
                //EndConnect threw an exception.
                //Most likely means the server refused the connection.
            }
        }
        else
        {
            //Connection timed out.
        }
    }
}