Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if port is in use? [duplicate]

Tags:

c#

wcf

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

like image 604
Joel Martinez Avatar asked Mar 24 '09 22:03

Joel Martinez


2 Answers

You cannot determine if a port is available. You can only determine

  1. That you have control of a port
  2. That a port was available at some point in the past

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.

like image 176
JaredPar Avatar answered Sep 18 '22 17:09

JaredPar


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;
}
like image 26
Andreas Reiff Avatar answered Sep 20 '22 17:09

Andreas Reiff