1.IP 掩码范围计算
输入 127.0.0.1/24
输出 127.0.0.0 – 127.0.0.255 的所有IP

GenIpSegment("127.0.0.1",24);
//项目设置为允许执行 unsafe 代码
unsafe static void GenIpSegment(string ipStr, uint mask)
{
    uint ip = 0;
    byte* ipSegment = (byte*)&ip;
    var ipSplit = ipStr.Split('.');
    for (int i = 0; i < ipSplit.Length; i++)
    {
        ipSegment[3 - i] = byte.Parse(ipSplit[i]);
    }
    var mask1 = System.Runtime.Intrinsics.X86.Bmi2.ZeroHighBits(~0u, 32 - mask);
    var mask2 = ~mask1;
    ip = ip & mask2;
    var max = ip + mask1;
    for (; ip <= max; ip++)
    {
        Console.WriteLine($"{ipSegment[3].ToString()}.{ipSegment[2].ToString()}.{ipSegment[1].ToString()}.{ipSegment[0].ToString()}");
    }
}

 

2.生成起始IP段和结束IP段之间的地址
输入 127.0.0.1 127.0.1.255
输出 127.0.0.1 – 127.0.0.255 – 127.0.1.0 – 127.0.1.255 的所有IP

public static List GetIpDistance(string StartIp, string EndIp)
{
    uint IStartIp = IpInt(StartIp);
    uint IEndIp = IpInt(EndIp);
    List IpListInfo = new List();

    if (IEndIp >= IStartIp)
    {
        for (uint ip = IStartIp; ip <= IEndIp; ip++)
        {
            IpListInfo.Add(IntIp(ip));
        }
    }
    return IpListInfo;
}
public static uint IpInt(string ipStr)
{
    string[] ip = ipStr.Split('.');
    uint ipcode = 0xFFFFFF00 | byte.Parse(ip[3]);
    ipcode = ipcode & 0xFFFF00FF | (uint.Parse(ip[2]) << 0x08);
    ipcode = ipcode & 0xFF00FFFF | (uint.Parse(ip[1]) << 0x10);
    ipcode = ipcode & 0x00FFFFFF | (uint.Parse(ip[0]) << 0x18); return ipcode; } public static string IntIp(uint ipcode) { byte addr1 = (byte)((ipcode & 0xFF000000) >> 0x18);
    byte addr2 = (byte)((ipcode & 0x00FF0000) >> 0x10);
    byte addr3 = (byte)((ipcode & 0x0000FF00) >> 0x08);
    byte addr4 = (byte)(ipcode & 0x000000FF);
    return string.Format("{0}.{1}.{2}.{3}", addr1, addr2, addr3, addr4);
}