例如:
127.0.0.1 = 2130706433
127.0.0.255 = 2130706687
判断:
127.0.1.253 = 2130706941
是否在此范围内,直接比较整数大小即可
将ip地址转换成整数
public static long IP2Long(string ip)
{
//code from www.sharejs.com
string[] ipBytes;
double num = 0;
if(!string.IsNullOrEmpty(ip))
{
ipBytes = ip.Split('.');
for (int i = ipBytes.Length - 1; i >= 0; i--)
{
num += ((int.Parse(ipBytes[i]) % 256) * Math.Pow(256, (3 - i)));
}
}
return (long)num;
}
//该代码片段来自于: http://www.sharejs.com/codes/csharp/8681
判断给定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!
}
//该代码片段来自于: http://www.sharejs.com/codes/csharp/8681
原文转自:脚本分享网 http://www.sharejs.com/codes/csharp/8681