比如给定一个ip段:127.0.0.1 ~ 127.0.0.255,我们想判断一个给定的ip地址是否在此段内,可以先将ip地址转换成整数,然后整数比较大小就很容易了。
例如:
127.0.0.1 = 2130706433
127.0.0.255 = 2130706687
判断:
127.0.1.253 = 2130706941
是否在此范围内,直接比较整数大小即可
将ip地址转换成整数:
public static long IP2Long(string ip)
{
string[] ipBytes;
double num = ;
if(!string.IsNullOrEmpty(ip))
{
ipBytes = ip.Split('.');
for (int i = ipBytes.Length - ; i >= ; i--)
{
num += ((int.Parse(ipBytes[i]) % ) * Math.Pow(, ( - i)));
}
}
return (long)num;
}
判断给定ip地址是否在指定范围内:
long
start = IP2Long(
"127.0.0.1"
);
long
end = IP2Long(
"127.0.0.255"
);
long
ipAddress = IP2Long(
"127.0.1.253"
);
bool
inRange = (ipAddress >= start && ipAddress <= end);
if
(inRange){
//IP Address fits within range!
}