Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C# 3.5
Tip/Trick

Find an open port on a machine using C#

Rate me:
Please Sign up or sign in to vote.
4.79/5 (13 votes)
13 Oct 2011CPOL 67K   8   8
How to find an open port in a machine using C#.
Include these namespaces in your class:
C#
using System.Net.NetworkInformation;
using System.Net;

The actual method to get the first open port from the system is as follows:
C#
private string GetOpenPort()
{
  int PortStartIndex = 1000;
  int PortEndIndex = 2000;
  IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
  IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();
 
  List<int> usedPorts = tcpEndPoints.Select(p => p.Port).ToList<int>();
  int unusedPort = 0;

  for (int port = PortStartIndex; port < PortEndIndex; port++)
  {
     if (!usedPorts.Contains(port))
     {
        unusedPort = port;
        break;
     }
  }
  return unusedPort.ToString();
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
Software developer by profession, working for a service and product based organisation in India.

Career graph:
Software Programmer since 2002.
Web Developer in ASP.NET since 2004.

Interests:
I love reading the blogs and articles of technology experts. I love codeproject and stackoverflow .

I love to share knowledge and help the programmers. I appreciate if some body corrects my code or my concepts which helps me learn.

Comments and Discussions

 
SuggestionTitle is a bit misleading Pin
Topheman6-Jul-14 12:37
Topheman6-Jul-14 12:37 
GeneralMy vote of 4 Pin
shaijujanardhanan19-Nov-12 20:37
shaijujanardhanan19-Nov-12 20:37 
My app was having port conflicts..your code gave me a hint on how to solve it..Thanx a lot
GeneralReason for my vote of 5 Good one Pin
Emanuel DSouza28-Feb-12 19:29
Emanuel DSouza28-Feb-12 19:29 
GeneralI would like to point out that a new connection could be mad... Pin
Daniel.Grondal17-Oct-11 20:31
Daniel.Grondal17-Oct-11 20:31 
GeneralReason for my vote of 5 Good trick. Pin
Sergio Andrés Gutiérrez Rojas17-Oct-11 19:25
Sergio Andrés Gutiérrez Rojas17-Oct-11 19:25 
GeneralI think the functions name is wrong. It's not returning an o... Pin
Reto Ravasio13-Oct-11 13:19
Reto Ravasio13-Oct-11 13:19 
GeneralReason for my vote of 4 I suggest you included the necessary... Pin
ARBebopKid13-Oct-11 5:52
ARBebopKid13-Oct-11 5:52 
GeneralRe: Thank you USABebopKid. Implemented your suggestion Pin
bbirajdar13-Oct-11 5:55
bbirajdar13-Oct-11 5:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.