Skip to content

Instantly share code, notes, and snippets.

View TiTiKy441's full-sized avatar

TiTiKy TiTiKy441

  • Moscow
  • 10:14 - 3h ahead
View GitHub Profile
@TiTiKy441
TiTiKy441 / GetIPV4AddressUint.cs
Created June 2, 2025 11:47
IPv4 address to uint C# using stackalloc
public static uint GetIPV4AddressUint(IPAddress ipAddr)
{
if (ipAddr.AddressFamily is not AddressFamily.InterNetwork) throw new InvalidOperationException("GetIPV4AddressUint supports only ipv4 addresses");
Span<byte> addrBytes = stackalloc byte[4];
if (!ipAddr.TryWriteBytes(addrBytes, out int _)) throw new InvalidDataException("Unable to get ip address bytes");
return ((uint)addrBytes[3] << 24) + ((uint)addrBytes[2] << 16) + ((uint)addrBytes[1] << 8) + addrBytes[0];
}