using System.Collections.Generic;
using System.Net;
using System.Linq;
public class IPRange
{
public byte[] StartAddressBytes { get; private set; }
public byte[] EndAddressBytes { get; private set; }
public IPRange(IPAddress startAddress, IPAddress endAddress)
{
StartAddressBytes = startAddress.GetAddressBytes();
EndAddressBytes = endAddress.GetAddressBytes();
}
public IPRange(string strartIp, string endIp)
{
IPAddress startAddress, endAddress;
if (IPAddress.TryParse(strartIp, out startAddress)
&& IPAddress.TryParse(endIp, out endAddress))
{
StartAddressBytes = startAddress.GetAddressBytes();
EndAddressBytes = endAddress.GetAddressBytes();
}
}
}
//--------------------------
public class IPRangeUtil
{
public static bool IsInRange(List
{
IPAddress clientAddress;
if (!IPAddress.TryParse(clientIp, out clientAddress))
{
return false;
}
return IsInRange(ipRange, clientAddress);
}
public static bool IsInRange(
{
int clientIpSum = clientAddress.GetAddressBytes().Sum(item => item);
return ipRange.Where(range =>
clientIpSum >= range.StartAddressBytes.Sum(item => item)
&& clientIpSum <= range.EndAddressBytes.Sum(item => item)).Any() ;
}
}
A using is very easy:
List
{
//You can replace "xxx.xxx.xxx.xxx" to IPAddress typed variable
new IPRange("192.168.10.68", "192.168.10.255"),
new IPRange("192.168.0.68h", "192.168.10.68")
};
bool isInRange = IPRangeUtil.IsInRange(ranges, "192.168.10.70");
Enjoy!