-
-
Save pelengami/b5896162c851b1068123a3936c198a00 to your computer and use it in GitHub Desktop.
Get first available udp port
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
public bool TryGetFirstAvailableUdpPort(out int port) | |
{ | |
var startingAtPort = 5678; | |
var maxNumberOfPortsToCheck = 500; | |
var range = Enumerable.Range(startingAtPort, maxNumberOfPortsToCheck).ToList(); | |
var portsInUse = | |
from p in range | |
join used in System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners() | |
on p equals used.Port | |
select p; | |
var firstFreeUdpPortInRange = range.Except(portsInUse).FirstOrDefault(); | |
if (firstFreeUdpPortInRange > 0) | |
{ | |
port = firstFreeUdpPortInRange; | |
return true; | |
} | |
port = -1; | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment