Question

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?

Était-ce utile?

La solution

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).

Autres conseils

I created a tool just like this to ping all IP Addresses on a network and get the response back.

I used the .net 4.0 parallel for / foreach features for this. It increased the performance dramatically.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top