public class IPRegion
{
public static bool IPInRegion(string beginIP, string endIP, string inputIP)
{
IPAddress _beginip;
IPAddress _endip;
IPAddress _inputip;
try
{
_beginip = IPAddress.Parse(beginIP);
_endip = IPAddress.Parse(endIP);
_inputip = IPAddress.Parse(inputIP);
}
catch (Exception ex)
{
ErrorHandler.Handle(ex);
return false;
}
if (_beginip == null || _endip == null || _inputip == null) return false;
byte[] _beginbyte = _beginip.GetAddressBytes();
Int64 _beginint = ConvertIPToInt(_beginbyte);
byte[] _endbyte = _endip.GetAddressBytes();
Int64 _endint = ConvertIPToInt(_endbyte);
if (_beginint > _endint) return false;
byte[] _inputtype = _inputip.GetAddressBytes();
Int64 _inputint = ConvertIPToInt(_inputtype);
return (_inputint <= _endint && _inputint >= _beginint);
}
protected static Int64 ConvertIPToInt(byte[] _bytes)
{
if (_bytes.Length != 4) return 0;
string _intstring = "";
for (int i = 0; i < _bytes.Length; i++)
{
_intstring += FormatIPPart(_bytes[i].ToString());
}
Int64 _outputint;
return !Int64.TryParse(_intstring, out _outputint) ? 0 : _outputint;
}
protected static string FormatIPPart(string _ippart)
{
Regex _regx = new Regex(@"^\d{1,3}$");
if (!_regx.IsMatch(_ippart)) return "000";
while (_ippart.Length < 3)
{
_ippart = "0" + _ippart;
}
return _ippart;
}
}