diff --git a/src/Servers/Kestrel/Core/src/Systemd/KestrelServerOptionsSystemdExtensions.cs b/src/Servers/Kestrel/Core/src/Systemd/KestrelServerOptionsSystemdExtensions.cs
index 6def39159de2..bf8f0fe69437 100644
--- a/src/Servers/Kestrel/Core/src/Systemd/KestrelServerOptionsSystemdExtensions.cs
+++ b/src/Servers/Kestrel/Core/src/Systemd/KestrelServerOptionsSystemdExtensions.cs
@@ -11,11 +11,12 @@ namespace Microsoft.AspNetCore.Hosting
public static class KestrelServerOptionsSystemdExtensions
{
// SD_LISTEN_FDS_START https://www.freedesktop.org/software/systemd/man/sd_listen_fds.html
- private const ulong SdListenFdsStart = 3;
+ private const int SdListenFdsStart = 3;
private const string ListenPidEnvVar = "LISTEN_PID";
+ private const string ListenFdsEnvVar = "LISTEN_FDS";
///
- /// Open file descriptor (SD_LISTEN_FDS_START) initialized by systemd socket-based activation logic if available.
+ /// Open file descriptors (starting from SD_LISTEN_FDS_START) initialized by systemd socket-based activation logic if available.
///
///
/// The .
@@ -26,7 +27,7 @@ public static KestrelServerOptions UseSystemd(this KestrelServerOptions options)
}
///
- /// Open file descriptor (SD_LISTEN_FDS_START) initialized by systemd socket-based activation logic if available.
+ /// Open file descriptors (starting from SD_LISTEN_FDS_START) initialized by systemd socket-based activation logic if available.
/// Specify callback to configure endpoint-specific settings.
///
///
@@ -36,7 +37,16 @@ public static KestrelServerOptions UseSystemd(this KestrelServerOptions options,
{
if (string.Equals(Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture), Environment.GetEnvironmentVariable(ListenPidEnvVar), StringComparison.Ordinal))
{
- options.ListenHandle(SdListenFdsStart, configure);
+ // This matches sd_listen_fds behavior that requires %LISTEN_FDS% to be present and in range [1;INT_MAX-SD_LISTEN_FDS_START]
+ if (int.TryParse(Environment.GetEnvironmentVariable(ListenFdsEnvVar), NumberStyles.None, NumberFormatInfo.InvariantInfo, out var listenFds)
+ && listenFds > 0
+ && listenFds <= int.MaxValue - SdListenFdsStart)
+ {
+ for (var handle = SdListenFdsStart; handle < SdListenFdsStart + listenFds; ++handle)
+ {
+ options.ListenHandle((ulong)handle, configure);
+ }
+ }
}
return options;