Recently, I need to do something similar in ASP.NET Core. I went with the approach of using System.Net.IPAddress
to express the IP addresses as a byte
array. I then compared elements in the arrays to see if the subject IP address is within the range. This is a similar approach to answer given by CodesInChaos and Pabuc.
System.Net.IPAddress.TryParse(ipAddressRule.StartIpAddress, out var startIpAddress);
System.Net.IPAddress.TryParse(ipAddressRule.EndIpAddress, out var endIpAddress);
if (IsWithinAllowedIpAddresses(clientIpAddress.GetAddressBytes(), startIpAddress.GetAddressBytes(), endIpAddress.GetAddressBytes()))
{
...
}
public bool IsWithinAllowedIpAddresses(byte[] ipAddress, byte[] startAllowIpAddress, byte[] endAllowIpAddress)
{
if (ipAddress.Length != startAllowIpAddress.Length)
{
throw new ArgumentException();
}
if (ipAddress.Length != endAllowIpAddress.Length)
{
throw new ArgumentException();
}
for (int i = 0; i < ipAddress.Length; i++)
{
if (ipAddress[i] < startAllowIpAddress[I])
{
return false;
}
if (ipAddress[i] > endAllowIpAddress[I])
{
return false;
}
}
return true;
}