// Without setting SO_REUSEADDR on macOS and Linux, binding to a recently used endpoint can fail. // https://github.com/dotnet/corefx/issues/24562 private unsafe void EnableRebinding(Socket listenSocket) { var optionValue = 1; var setsockoptStatus = 0; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { setsockoptStatus = setsockopt(listenSocket.Handle.ToInt32(), SOL_SOCKET_LINUX, SO_REUSEADDR_LINUX, (IntPtr)(&optionValue), sizeof(int)); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { setsockoptStatus = setsockopt(listenSocket.Handle.ToInt32(), SOL_SOCKET_OSX, SO_REUSEADDR_OSX, (IntPtr)(&optionValue), sizeof(int)); } if (setsockoptStatus != 0) { _trace.LogInformation("Setting SO_REUSEADDR failed with errno '{errno}'.", Marshal.GetLastWin32Error()); } }