check if a port is opened

  • Thread starter Thread starter NoOne
  • Start date Start date
N

NoOne

Hi everybody!

I'm want to check if a certain port is opened or closed.
now I'm using try-catch to connect to the port. if it fails, it meas that
the port is closed.

The problem is that this method is extremely inefficient! anyone has a
better idea on how to do this kind of verification?

Thanks!
 
Hi,

There is no better way if after you check whether the port is free you
immediately try to use it.

The two statements (check and use) won't execute as an atomic operation.
Therefore, it's possible that you'll check for the port being in use and it
will be "false", and then you'll try to acquire its use and an exception will
be thrown because another process slipped in before you.

So if you have to code for the exception handling anyway to account for the
lack of synchronicity, there is no reason to check the port's status in the
first place.


Why is try...catch inefficient for you?
 
You could try something like this:

using System.Net.NetworkInformation;
using System.Net;

.....

IPGlobalProperties properties =
IPGlobalProperties.GetIPGlobalProperties();

IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();

foreach (IPEndPoint p in tcpEndPoints)
{
Console.WriteLine("port {0} busy",p.Port.ToString());

}

But you would also have to do the same for UDP using the
GetActiveUdpListeners as well. It would give you a decent indication of
what is busy.

Kelly S. Elias
Webmaster
DevDistrict - C# Code Library
http://devdistrict.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top