0

我正在尝试对给定的 IP 地址进行端口扫描,其范围为 20 个端口。我知道端口 80 是开放的,而所有其他端口都是关闭的。我的代码显示所有端口都是打开的。

我正在尝试使用异步 TCPClient 来实现端口扫描。

这里有什么问题?我错过了什么吗?

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

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

private void CallBack(IAsyncResult result)
{
    using (TcpClient client = (TcpClient)result.AsyncState)
    {
        try
        {
            this.Invoke((MethodInvoker)delegate
            {
                txtDisplay.Text += "open" + Environment.NewLine;
            });
        }
        catch
        {
            this.Invoke((MethodInvoker)delegate
            {
                txtDisplay.Text += "closed" + Environment.NewLine;
            });
        }
    }
}

这就是我现在拥有的 CallBack 方法:

    private void CallBack(IAsyncResult result)
    {
        using (TcpClient client = (TcpClient)result.AsyncState)
        {
            client.EndConnect(result);

            if (client.Connected)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    txtDisplay.Text += "open" + Environment.NewLine;
                });
            }
            else
            {
                this.Invoke((MethodInvoker)delegate
                {
                    txtDisplay.Text += "closed" + Environment.NewLine;
                });
            }
        }
    }
4

1 回答 1

1

该声明:

using (TcpClient client = new TcpClient())
{
    client.BeginConnect(IPAddress.Parse("74.125.226.84"), port, new AsyncCallback(CallBack), client);
}

创建一个新的 TcpClient,然后调用 BeginConnect,然后在到达回调之前立即释放客户端。请记住,BeginConnect 方法不是阻塞的。客户端的处理应该只发生在回调中,所以 ScanPort 方法应该是这样的:

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

在回调中,您还应该调用EndConnect

using (TcpClient client = (TcpClient)result.AsyncState)
{
    try
    {
        client.EndConnect(result);
        this.Invoke((MethodInvoker)delegate
        {
            txtDisplay.Text += "open" + Environment.NewLine;
        });
    }
    catch
    {
        this.Invoke((MethodInvoker)delegate
        {
            txtDisplay.Text += "closed" + Environment.NewLine;
        });
    }
于 2012-01-26T04:58:43.233 回答