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; }); } }
source share