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.
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.
The result is:
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.0to192.168.7.255, including the192.168.5.0through192.168.7.255that 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.