确定C#中IPv6 CIDR Notated值的起始IP /结束IP地址

时间:2017-07-12 15:02:49

标签: c# ipv6 biginteger cidr

我正在尝试确定C#中IPv6 CIDR Notated值的起始IP地址和结束IP地址(例如,2001:5::/32)。如果我将该值放入this website,我会得到:

Start Range: 2001:5:0:0:0:0:0:0
End Range: 2001:5:ffff:ffff:ffff:ffff:ffff:ffff
No. of host: 79228162514264337593543950336

当我通过我的方法运行它时,我的开始和结束都得到32.1.0.5。我的猜测是将结果转换为字节数组。我怎样才能更好地为我工作?

private bool GetIPAddressFromCIDR( string ipCIDR, out string startIP, out string endIP )
{
    startIP = endIP = "";
    try
    {
        string strAddress = ipCIDR.Substring( 0, ipCIDR.IndexOf( '/' ) );

        byte routingBitCount = Byte.Parse( ipCIDR.Substring( ipCIDR.IndexOf( '/' ) + 1 ) );
        IPAddress ipAddress = IPAddress.Parse( strAddress );


        if( ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 )
        {
            BigInteger ip = new BigInteger( ipAddress.GetAddressBytes() );

            byte BitSize = 128;
            BigInteger mask;
            if( routingBitCount == 0 )
            {
                mask = 0;
            }
            else
            {
                mask = unchecked( ~( ( 1 << routingBitCount ) - 1 ) );
            }

            BigInteger start = ip & mask;
            BigInteger end = ip | ~mask;

            startIP = new IPAddress( start.ToByteArray() ).ToString();
            endIP = new IPAddress( end.ToByteArray() ).ToString();
        }
        else
        {
            byte BitSize = 32;

            uint address = BitConverter.ToUInt32( ipAddress.GetAddressBytes(), 0 );
            uint mask = routingBitCount == 0 ? 0 : unchecked( ~( ( ( uint ) 1 << ( BitSize - routingBitCount ) ) - 1 ) );
            uint start = address & mask;
            uint end = start | ~mask;

            startIP = new IPAddress( start ).ToString();
            endIP = new IPAddress( end ).ToString();
        }
        return true;
    }
    catch( Exception ex )
    {
        return false;
    }
}

PS。请不要图书馆。我想让这段代码工作

0 个答案:

没有答案