Skip to content

Instantly share code, notes, and snippets.

@nonoesp
Created April 3, 2018 20:04
Show Gist options
  • Save nonoesp/f6c1c35be93adccb936c65f6ae65ba21 to your computer and use it in GitHub Desktop.
Save nonoesp/f6c1c35be93adccb936c65f6ae65ba21 to your computer and use it in GitHub Desktop.
GetAvailablePort(8080);
using System.Net.NetworkInformation;
// ..
// from https://stackoverflow.com/a/45384984
public static int GetAvailablePort(int startingPort)
{
var portArray = new List<int>();
var properties = IPGlobalProperties.GetIPGlobalProperties();
// Ignore active connections
var connections = properties.GetActiveTcpConnections();
portArray.AddRange(from n in connections
where n.LocalEndPoint.Port >= startingPort
select n.LocalEndPoint.Port);
// Ignore active tcp listners
var endPoints = properties.GetActiveTcpListeners();
portArray.AddRange(from n in endPoints
where n.Port >= startingPort
select n.Port);
// Ignore active udp listeners
endPoints = properties.GetActiveUdpListeners();
portArray.AddRange(from n in endPoints
where n.Port >= startingPort
select n.Port);
portArray.Sort();
for (var i = startingPort; i < UInt16.MaxValue; i++)
if (!portArray.Contains(i))
return i;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment