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 に答える