diff --git a/AssettoServer/Utils/SocketAddressExtensions.cs b/AssettoServer/Utils/SocketAddressExtensions.cs index 33e66d38..10d880b7 100644 --- a/AssettoServer/Utils/SocketAddressExtensions.cs +++ b/AssettoServer/Utils/SocketAddressExtensions.cs @@ -1,10 +1,14 @@ using System; using System.Net; +using System.Reflection; namespace AssettoServer.Utils; public static class SocketAddressExtensions { + private static readonly GetIPv4AddressMethod GetIPv4AddressDelegate; + private delegate uint GetIPv4AddressMethod(ReadOnlySpan buffer); + public static SocketAddress Clone(this SocketAddress address) { var clone = new SocketAddress(address.Family, address.Size); @@ -14,7 +18,19 @@ public static SocketAddress Clone(this SocketAddress address) public static bool IpEquals(this SocketAddress address, SocketAddress other) { - // This works for IPv4 only. First two bytes = port, next 4 bytes = address - return address.Buffer.Span[2..6].SequenceEqual(other.Buffer.Span[2..6]); + return address.GetIPv4Address() == other.GetIPv4Address(); + } + + public static uint GetIPv4Address(this SocketAddress address) + { + return GetIPv4AddressDelegate(address.Buffer.Span); + } + + static SocketAddressExtensions() + { + GetIPv4AddressDelegate = Assembly.GetAssembly(typeof(SocketAddress))! + .GetType("System.Net.SocketAddressPal")! + .GetMethod("GetIPv4Address", BindingFlags.Public | BindingFlags.Static)! + .CreateDelegate(); } }