Advertisement
uwekeim

FreePortDetector.cs

Feb 28th, 2024
776
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.49 KB | Source Code | 0 0
  1. namespace Example;
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Linq;
  7. using System.Net.NetworkInformation;
  8.  
  9. public static class FreePortDetector
  10. {
  11.     private static readonly List<int> ReservedPorts = [];
  12.  
  13.     public static bool IsPortFree(int port)
  14.     {
  15.         if (ReservedPorts.Contains(port))
  16.         {
  17.             return false;
  18.         }
  19.         else
  20.         {
  21.             // http://stackoverflow.com/a/570126/107625
  22.  
  23.             var globalProperties = IPGlobalProperties.GetIPGlobalProperties();
  24.             var informations = globalProperties.GetActiveTcpListeners();
  25.  
  26.             return informations.All(information => information.Port != port);
  27.         }
  28.     }
  29.  
  30.     public static void RemovePort(int port)
  31.     {
  32.         ReservedPorts.Remove(port);
  33.     }
  34.  
  35.     public static int GetFreePort()
  36.     {
  37.         if (int.TryParse(ConfigurationManager.AppSettings[@"webserver.listenPort"], out var alt) && alt > 0)
  38.         {
  39.             alt += ReservedPorts.Count;
  40.             if (IsPortFree(alt))
  41.             {
  42.                 ReservedPorts.Add(alt);
  43.                 return alt;
  44.             }
  45.         }
  46.  
  47.         // --
  48.  
  49.         for (var i = 0; i < 10; ++i)
  50.         {
  51.             var port = Random.Shared.Next(9000, 15000);
  52.             if (IsPortFree(port))
  53.             {
  54.                 ReservedPorts.Add(port);
  55.                 return port;
  56.             }
  57.         }
  58.  
  59.         throw new("No free port could be found.");
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement