Created
June 2, 2025 11:47
-
-
Save TiTiKy441/37be89eb1d22722a2b87d49863d0490f to your computer and use it in GitHub Desktop.
IPv4 address to uint C# using stackalloc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment