Click here to Skip to main content
Click here to Skip to main content

Tagged as

Find an open port on a machine using C#

, 13 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
How to find an open port in a machine using C#.
Include these namespaces in your class:
using System.Net.NetworkInformation;
using System.Net;
The actual method to get the first open port from the system is as follows:
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)

Share

About the Author

aspnet -i
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 [modified] PinmemberTopheman6-Jul-14 12:37 
GeneralMy vote of 4 Pinmembershaijujanardhanan19-Nov-12 20:37 
GeneralReason for my vote of 5 Good one PinmemberEmanuel DSouza28-Feb-12 19:29 
GeneralI would like to point out that a new connection could be mad... PinmemberDaniel.Grondal17-Oct-11 20:31 
GeneralReason for my vote of 5 Good trick. PinmemberSergio Andrés Gutiérrez Rojas17-Oct-11 19:25 
GeneralI think the functions name is wrong. It's not returning an o... PinmemberReto Ravasio13-Oct-11 13:19 
GeneralReason for my vote of 4 I suggest you included the necessary... PinmemberUSABebopKid13-Oct-11 5:52 
GeneralRe: Thank you USABebopKid. Implemented your suggestion PinmemberBalaji Birajdar13-Oct-11 5:55 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.141022.2 | Last Updated 13 Oct 2011
Article Copyright 2011 by aspnet -i
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid