Why IAsyncResult report all port as opened?

后端 未结 1 490
感动是毒
感动是毒 2021-01-16 10:00

i have this method running in a thread , but when i test it report all ports as open. it seems that the method : var result = client.BeginConnect(host, port, null, nul

相关标签:
1条回答
  • 2021-01-16 10:49

    Determine if the port is open based upon a non-Exception when executing EndConnect.

    Example of a serial port scan:

    Note: Use some Linq to break your port list into groups and perform a Parallel.ForEach if you wish to scan multiple ports at the same time (a concurrency of 4 works well and does not overwhelm the Android network stack).

    bool portOpen;
    for (int portNo = 1; portNo < (fasttScan ? 1025 : 65537); portNo++)
    {
        TcpClient client = new TcpClient
        {
            SendTimeout = (fasttScan ? 2 : 10),
            ReceiveTimeout = (fasttScan ? 2 : 10)
        };
        var tcpClientASyncResult = client.BeginConnect(ipAddress, portNo, asyncResult =>
        {
            portOpen = false;
            try
            {
                client.EndConnect(asyncResult);
                portOpen = true;
            }
            catch (SocketException)
            {
            }
            catch (NullReferenceException)
            {
            }
            catch (ObjectDisposedException)
            {
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message); // ? unknown socket failure ?
            }
            if (portOpen)
                Console.WriteLine($"{ipAddress}:{portNo}:{portOpen}");
            client.Dispose();
            client = null;
        }, null);
        tcpClientASyncResult.AsyncWaitHandle.WaitOne();
    }
    
    0 讨论(0)
提交回复
热议问题