diff --git a/src/Tgstation.Server.Host/Extensions/SocketExtensions.cs b/src/Tgstation.Server.Host/Extensions/SocketExtensions.cs index 28c94f0ba2..baae23e7d7 100644 --- a/src/Tgstation.Server.Host/Extensions/SocketExtensions.cs +++ b/src/Tgstation.Server.Host/Extensions/SocketExtensions.cs @@ -1,4 +1,5 @@ -using System.Net; +using System; +using System.Net; using System.Net.Sockets; namespace Tgstation.Server.Host.Extensions @@ -15,24 +16,32 @@ namespace Tgstation.Server.Host.Extensions /// If IPV6 should be tested as well. public static void BindTest(ushort port, bool includeIPv6) { - using var socket = new Socket( - includeIPv6 - ? AddressFamily.InterNetworkV6 - : AddressFamily.InterNetwork, - SocketType.Stream, - ProtocolType.Tcp); - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true); - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); - if (includeIPv6) - socket.DualMode = true; - - socket.Bind( - new IPEndPoint( + void BindSocket(bool forCleanup) + { + using var socket = new Socket( includeIPv6 - ? IPAddress.IPv6Any - : IPAddress.Any, - port)); + ? AddressFamily.InterNetworkV6 + : AddressFamily.InterNetwork, + SocketType.Stream, + ProtocolType.Tcp); + + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, !forCleanup); + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, forCleanup); + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); + if (includeIPv6) + socket.DualMode = true; + + socket.Bind( + new IPEndPoint( + includeIPv6 + ? IPAddress.IPv6Any + : IPAddress.Any, + port)); + } + + GC.Collect(Int32.MaxValue, GCCollectionMode.Forced, true, false); + BindSocket(false); + BindSocket(true); } } }