using System; using System.Management; using System.Runtime.Versioning; #nullable enable namespace Duplicati.Library.Utility; /// /// Class for reading the machine name /// public static class MachineNameReader { /// /// Makes a best effort to get the machine name /// /// The machine name public static string GetMachineName() { string? machineName = null; if (OperatingSystem.IsWindows()) machineName = GetMachineNameWindows(); else if (OperatingSystem.IsMacOS()) machineName = GetMachineNameMacOS(); else if (OperatingSystem.IsLinux()) machineName = GetMachineNameLinux(); return string.IsNullOrWhiteSpace(machineName) ? Environment.MachineName : machineName; } /// /// Executes a command and reads the output /// /// The command to execute /// The arguments to pass to the command /// The output of the command private static string ExecuteAndReadOutput(string command, string arguments) { try { var process = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo { FileName = command, Arguments = arguments, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true } }; process.Start(); process.WaitForExit(TimeSpan.FromSeconds(1)); if (!process.HasExited) { process.Kill(); return string.Empty; } if (process.ExitCode != 0) return string.Empty; return process.StandardOutput.ReadToEnd().Trim(); } catch { return string.Empty; } } /// /// Gets the machine name if running MacOS /// /// The machine name [SupportedOSPlatform("macos")] private static string? GetMachineNameMacOS() => ExecuteAndReadOutput("scutil", "--get ComputerName"); /// /// Gets the machine name if running Windows /// /// The machine name [SupportedOSPlatform("windows")] private static string? GetMachineNameWindows() => null; // No special handling for Windows, always uses NetBIOS name /// /// Gets the machine name if running Linux /// /// The machine name [SupportedOSPlatform("linux")] private static string? GetMachineNameLinux() => null; // No special handling for Linux, always uses hostname }