34 lines
970 B
C#
34 lines
970 B
C#
using System.Net;
|
|
using System.Net.Sockets;
|
|
|
|
namespace DataTransfer.Security;
|
|
|
|
public static class ClientAddress
|
|
{
|
|
/// <summary>
|
|
/// Groups remote addresses that one client typically controls: an IPv4 address or an IPv6 /56 prefix. Subscribers
|
|
/// usually get a /56 or more, so limiting single IPv6 addresses or /64 networks would be pointless.
|
|
/// </summary>
|
|
public static string GetPartitionKey(IPAddress? address)
|
|
{
|
|
if (address is null)
|
|
{
|
|
return "unknown";
|
|
}
|
|
|
|
if (address.IsIPv4MappedToIPv6)
|
|
{
|
|
address = address.MapToIPv4();
|
|
}
|
|
|
|
if (address.AddressFamily != AddressFamily.InterNetworkV6)
|
|
{
|
|
return address.ToString();
|
|
}
|
|
|
|
Span<byte> bytes = stackalloc byte[16];
|
|
address.TryWriteBytes(bytes, out _);
|
|
bytes[7..].Clear();
|
|
return $"{new IPAddress(bytes)}/56";
|
|
}
|
|
}
|