I'm creating a small tool which let me to check status of ports of given IP and port number like this:
private void ScanPort(IPAddress address, int port)
{
using (TcpClient client = new TcpClient())
{
try
{
client.Connect(address, port);
txtDisplay.AppendText("Port: " + nudFrom.Value.ToString() +
" is open." + Environment.NewLine);
}
catch (SocketException)
{
txtDisplay.AppendText("Port: " + nudFrom.Value.ToString() +
" is closed." + Environment.NewLine);
}
}
}
The problem is that when port is open it takes about a second to check and if port is closed the process takes about 20 seconds time.
How to make checking for open/closed ports quicker?
One option would be to implement this using raw sockets in something like SharpPcap or Pcap.NET and catching the ICMP failure response. A simpler approach would be to look into reducing the timeout. Here's some ideas on how to do it. Here's a related question that might also help.
If you're strictly looking for ways to improve the performance of the code you posted then you may consider pinging the address prior to attempting to connect to it (assuming this is related to your prior question about ARP'ing remote hosts), and since String is immutable the +
operator is generally slower than using something like String.Format
. These suggestions will not cut seconds off your processing though (in fact you'll likely be unable to tell a difference).