From 6fb70ebd601c4f7d8b8f9d535b899bcaeb564145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gu=C3=B0mundur=20Hrei=C3=B0arsson?= Date: Tue, 5 Aug 2025 15:58:49 +0200 Subject: [PATCH] Remove need for machine to have a valid hostname in IdGenerator --- .../StronglyTypedIds/IdGenerator.cs | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/application/shared-kernel/SharedKernel/StronglyTypedIds/IdGenerator.cs b/application/shared-kernel/SharedKernel/StronglyTypedIds/IdGenerator.cs index d1f99a5aa..d64656dac 100644 --- a/application/shared-kernel/SharedKernel/StronglyTypedIds/IdGenerator.cs +++ b/application/shared-kernel/SharedKernel/StronglyTypedIds/IdGenerator.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net.NetworkInformation; using System.Net.Sockets; namespace PlatformPlatform.SharedKernel.StronglyTypedIds; @@ -33,12 +33,28 @@ public static long NewId() /// private static int GetUniqueGeneratorIdFromIpAddress() { - var host = Dns.GetHostEntry(Dns.GetHostName()); const string noNetworkAdapters = "No network adapters with an IPv4 address in the system. IdGenerator is meant to create unique IDs across multiple machines, and requires an IP address to do so."; - var ipAddress = Array.Find(host.AddressList, ip => ip.AddressFamily == AddressFamily.InterNetwork) - ?? throw new InvalidOperationException(noNetworkAdapters); - var lastSegment = ipAddress.ToString().Split('.')[3]; - return int.Parse(lastSegment); + var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces() + .Where(ni => ni.OperationalStatus == OperationalStatus.Up && + ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && + ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel + ) + .ToArray(); + + foreach (var networkInterface in networkInterfaces) + { + var properties = networkInterface.GetIPProperties(); + var ipv4Address = properties.UnicastAddresses + .FirstOrDefault(addr => addr.Address.AddressFamily == AddressFamily.InterNetwork); + + if (ipv4Address is not null) + { + var lastSegment = ipv4Address.Address.ToString().Split('.')[3]; + return int.Parse(lastSegment); + } + } + + throw new InvalidOperationException(noNetworkAdapters); } }