簡體   English   中英

生成位於IPv6起始值和終止值之間的IP

[英]Generate IP which lie in between start and end values of IPv6

對於IPv6,我需要生成位於給定起始IP和結束IP之間的所有IP。

例如,假設起始IP為2001:db8:85a3:42:1000:8a2e:370:7334 ,結束IP為2001:db8:85a3:42:1000:8a2e:370:7336.

我需要獲取介於兩者之間的所有IP。

問候

你可以:

public static IEnumerable<IPAddress> FromTo(IPAddress from, IPAddress to)
{
    if (from == null || to == null)
    {
        throw new ArgumentNullException(from == null ? "from" : "to");
    }

    if (from.AddressFamily != to.AddressFamily)
    {
        throw new ArgumentException("from/to");
    }

    long scopeId;

    // ScopeId can be used only for IPv6
    if (from.AddressFamily == AddressFamily.InterNetworkV6)
    {
        if (from.ScopeId != to.ScopeId)
        {
            throw new ArgumentException("from/to");
        }

        scopeId = from.ScopeId;
    }
    else
    {
        scopeId = 0;
    }

    byte[] bytesFrom = from.GetAddressBytes();
    byte[] bytesTo = to.GetAddressBytes();

    while (true)
    {
        int cmp = Compare(bytesFrom, bytesTo);

        if (cmp > 0)
        {
            break;
        }

        if (scopeId != 0)
        {
            // This constructor can be used only for IPv6
            yield return new IPAddress(bytesFrom, scopeId);
        }
        else
        {
            yield return new IPAddress(bytesFrom);
        }

        // Second check to handle case 255.255.255.255-255.255.255.255
        if (cmp == 0)
        {
            break;
        }

        Increment(bytesFrom);
    }
}

private static int Compare(byte[] x, byte[] y)
{
    for (int i = 0; i < x.Length; i++)
    {
        int ret = x[i].CompareTo(y[i]);

        if (ret != 0)
        {
            return ret;
        }
    }

    return 0;
}

private static void Increment(byte[] x)
{
    for (int i = x.Length - 1; i >= 0; i--)
    {
        if (x[i] != 0xFF)
        {
            x[i]++;
            return;
        }

        x[i] = 0;
    }
}

接着:

var addr1 = IPAddress.Parse("2001:db8:85a3:42:1000:8a2e:370:7334");
var addr2 = IPAddress.Parse("2001:db8:85a3:42:1000:8a2e:371:7336");

foreach (IPAddress addr in FromTo(addr1, addr2))
{
    Console.WriteLine(addr);
}

請注意,按照編寫的方式,該代碼與具有范圍ID的IPv4,IPv6和IPv6兼容(例如2001:db8:85a3:42:1000:8a2e:370:7334%100

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM