uwekeim icon

FreePortDetector.cs

uwekeim | PRO | 02/29/24 04:26:37 AM UTC | 0 ⭐ | 13441 👁️ | Never ⏰ | [C#, free, Detection, port, free port]
C# |

1.49 KB

|

Source Code

|

0 👍

/

0 👎

namespace Example;
 
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.NetworkInformation;
 
public static class FreePortDetector
{
    private static readonly List<int> ReservedPorts = [];
 
    public static bool IsPortFree(int port)
    {
        if (ReservedPorts.Contains(port))
        {
            return false;
        }
        else
        {
            // http://stackoverflow.com/a/570126/107625
 
            var globalProperties = IPGlobalProperties.GetIPGlobalProperties();
            var informations = globalProperties.GetActiveTcpListeners();
 
            return informations.All(information => information.Port != port);
        }
    }
 
    public static void RemovePort(int port)
    {
        ReservedPorts.Remove(port);
    }
 
    public static int GetFreePort()
    {
        if (int.TryParse(ConfigurationManager.AppSettings[@"webserver.listenPort"], out var alt) && alt > 0)
        {
            alt += ReservedPorts.Count;
            if (IsPortFree(alt))
            {
                ReservedPorts.Add(alt);
                return alt;
            }
        }
 
        // --
 
        for (var i = 0; i < 10; ++i)
        {
            var port = Random.Shared.Next(9000, 15000);
            if (IsPortFree(port))
            {
                ReservedPorts.Add(port);
                return port;
            }
        }
 
        throw new("No free port could be found.");
    }
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎