Is there a way, using C#, to determine if a port is available? I'd like to check before I start up a WCF ServiceHost instance using a port that's already used :-)
You cannot determine if a port is available. You can only determine
Unless you control the port by having a particular socket bound and listening on the port, it's possible for another process to come along and take control of the port.
The only reliable way to know if a port is available is to attempt to listen on it. If you succeed then the port is available and you have control. Otherwise you know that at some point in the past and potentially the present, the port was controlled by another entity.
As for In C#, how to check if a TCP port is available?, I think the original poster is not really sure if he is talking about client or server, so also the answers are either about client wanting to connect or server wanting to listen on a port.
JaredPar's answer is correct (more than this one!) though sometimes maybe inconvenient.
If you are reasonably certain that no other server is grabbing the port you just checked (or don't care for occasional failure), you can try (from http://www.codeproject.com/Tips/268108/Find-the-open-port-on-a-machine-using-Csharp?msg=4176410#xx4176410xx , similar to https://stackoverflow.com/a/570461/586754):
public static int GetOpenPort(int startPort = 2555)
{
int portStartIndex = startPort;
int count = 99;
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();
List<int> usedPorts = tcpEndPoints.Select(p => p.Port).ToList<int>();
int unusedPort = 0;
unusedPort = Enumerable.Range(portStartIndex, 99).Where(port => !usedPorts.Contains(port)).FirstOrDefault();
return unusedPort;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With