Created
October 9, 2022 20:21
-
-
Save coenm/2e384c5ed389a376a2bc8fda5b52494d to your computer and use it in GitHub Desktop.
FreePortLocator
This file contains hidden or 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; | |
| using System.Net.Sockets; | |
| public static class FreePortLocator | |
| { | |
| private static readonly IPEndPoint _defaultLoopbackEndpoint = new(IPAddress.Loopback, port: 0); | |
| public static int GetAvailablePort() | |
| { | |
| using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
| socket.Bind(_defaultLoopbackEndpoint); | |
| return ((IPEndPoint)socket.LocalEndPoint!).Port; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment