最近一个项目中用到了ip地址的自动生成。把几个相关的操作类发上来:
/// <summary>
/// 更具网段来获取相应IP的区间
/// </summary>
/// <param name="IP"></param>
/// <param name="Masklen"></param>
/// <returns></returns>
public static List<long> GetConstraintsIp(string IP, int Masklen)
{
List<long> ipArea = new List<long>();
string[] Iptmp = IP.Split('.');
uint minIP = 0;
uint maxIP = 0;
uint iIP = 0;
uint iMask = 0xFFFFFFFF; // 把子网掩码设置为 255.255.255.255
Masklen = 32 - Masklen; // MaskLen表标,bit位值等于1的个数,被32减了之后就变成了,bit位 0 的个数了,
iMask <<= Masklen; // 把子网掩码向左移 bit位值为0 的位数,这样就可以把以数字表示的子网掩码变成32位数的掩码了
//IPAddress ipaddress = IPAddress.Parse(IP); // 把IP从字符串的表示形式改成整型的形式
iIP = (uint)Ip2long(IP);
minIP = iIP & iMask;
ipArea.Add(minIP);
double sum =0;
for (int j = 0; j < Masklen; j++)
{
sum += Math.Pow(2, j);
}
maxIP = minIP | (uint)sum;
ipArea.Add(maxIP);
return ipArea;
}
/// <summary>
/// ip转化为整数
/// </summary>
/// <param name="l"></param>
/// <returns></returns>
public static IPAddress long2Ip(long l)
{
var b = new byte[4];
for (int i = 0; i < 4; i++)
{
b[3 - i] = (byte)(l >> 8 * i & 255);
}
return new IPAddress(b);
}
/// <summary>
/// 整数转化为ip
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static long Ip2long(string ip)
{
IPAddress curIp = IPAddress.Parse(ip);
int x = 3;
long o = 0;
foreach (byte f in curIp.GetAddressBytes())
{
o += (long)f << 8 * x--;
}
return o;
}