wrong output from Supernetting algorithm

41 Views Asked by At

I'm trying to implement a function that Supernetting the given list of sub-networks and returns the largest possible network/s, but it doesn't work correctly, the problem is that it returns outputs that isn't correct, the function was generated by Ai and I tried to modify it a lot and couldn't fix it, either Ai :)

this is the final update of the function I have tried:

QStringList IPSupernetting::calculateSupernet(const QStringList& subnets) {
    uint32_t commonPrefix = 0xFFFFFFFF;
    int maxPrefixLength = 0;

    for (const QString& subnet : subnets) {
        QStringList parts = subnet.split('/');
        if (parts.size() != 2) continue;

        QString networkAddress = parts[0];
        int prefixLength = parts[1].toInt();

        QHostAddress address(networkAddress);
        if (address.isNull() || address.protocol() != QAbstractSocket::IPv4Protocol)
            continue;

        quint32 ipv4Address = address.toIPv4Address();
        quint32 mask = 0xFFFFFFFF << (32 - prefixLength);
        commonPrefix &= (ipv4Address & mask);

        maxPrefixLength = std::max(maxPrefixLength, prefixLength);
    }

    QString supernet = QHostAddress(commonPrefix).toString() + "/" + QString::number(maxPrefixLength);
    QStringList result;
    result.append(supernet);

    return result;
}

and for testing the function, in main function I pass this list to the function then loop through it:

    IPSupernetting inv;
    QStringList subnets = {
           "192.168.0.0/24",
           "10.0.0.0/16",
           "172.16.0.0/20",
           "192.0.2.0/24",
           "10.10.10.0/24"
    };

    foreach (QString subnet, inv.calculateSupernet(subnets)) {
            qDebug() << "Calculated Supernet:" << subnet;
    };

it outputs: "0.0.0.0/24", which is incorrect.

1

There are 1 best solutions below

2
Ron Maupin On

You must simply start at the highest-order bit to count the number of common bits. That would be your prefix, zero the uncommon bits, and the number of common bits is the prefix length.

192.168.0.0/24 = 110000001010100000000 00000000000
192.168.1.0/24 = 110000001010100000000 00100000000
192.168.2.0/24 = 110000001010100000000 01000000000
192.168.3.0/24 = 110000001010100000000 01100000000
192.168.4.0/24 = 110000001010100000000 10000000000
                |   21 Common Bits    | Uncommon  |

The result is:

 110000001010100000000 00000000000 = 192.168.0.0/21
|   21 Common Bits    | Zero Bits |

This two-part answer explains it all.

Also, remember that you may aggregate more addressing than just those prefixes you want to aggregate. The above example aggregates every address from 192.168.0.0 to 192.168.7.255, including the 192.168.5.0 through 192.168.7.255 that are not included in your original list.

There is no single network aggregation that only includes the above networks without leaving out or including more addresses than you want.