Created
April 3, 2018 20:04
-
-
Save nonoesp/f6c1c35be93adccb936c65f6ae65ba21 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
GetAvailablePort(8080); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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