The dotted decimal notation of an IPv4 address is just a friendly way of writing a 32-bit int: we take each byte, write out its decimal representation, and separate them with periods.
Each IP address can therefore just be represented as a 32-bit int, and these can be directly compared.
The 4 raw bytes of the IPv4 address can be read with IPAddress.GetAddressBytes()
. From there, we can use BinaryPrimitives.ReadUInt32BigEndian
as an easy way to convert these into a big-endian unsigned 32-bit integer:
var ipAddress = IPAddress.Parse("127.0.0.1");
uint ipInt = BinaryPrimitives.ReadUInt32BigEndian(ipAddress.GetAddressBytes());
You can then compare your two uints
in the normal way.
If you want to compare the IP addresses as signed ints, rather than unsigned ints, you can do the similar:
var ipAddress = IPAddress.Parse("127.0.0.1");
int ipInt = BinaryPrimitives.ReadInt32BigEndian(ipAddress.GetAddressBytes());
BinaryPrimitives
was introduced in .NET Standard 2.1. If you're stuck on something older, you can use BitConverter
. However, BitConverter
uses the host's endianness, whereas the bytes in an IP address are always big-endian, so you'll have to convert between them:
uint ipInt = unchecked((uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(ipAddress.GetAddressBytes())));
For the signed version, it's a bit simpler:
int ipInt = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(ipAddress.GetAddressBytes()));