How to speed up the process of scanning TCP ports?

I am trying to scan TCP ports asynchronously. Since open ports only take a few hundredth of a millisecond to complete them, everything is fine, but when the ports are closed, I have to wait for an answer.

So what happens, I launch the application and almost immediately see that port 80 is open. Then I have to wait half a minute for all other ports to be scanned.

EDIT. plus I would like to show the reaction of how this happens, and not wait for other ports to be checked.

How to make it faster?

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; }); } } 
+6
source share
1 answer

You can use the WaitHandle BeginConnect return only to wait so long.

 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. } } } 
+7
source

Source: https://habr.com/ru/post/906974/


All Articles