in src/PSRule.Rules.Azure/Data/Template/CidrParsing.cs [281:353]
static string FormatIPAddress(byte[] ip)
{
if (ip.Length == 4)
{
// IPv4
return $"{ip[0]}.{ip[1]}.{ip[2]}.{ip[3]}";
}
// IPv6
// Find the longest sequence of consecutive zero bytes
var longestZeroStart = -1;
var longestZeroLength = 0;
var currentZeroStart = -1;
var currentZeroLength = 0;
for (var i = 0; i < ip.Length; i += 2)
{
if (ip[i] == 0 && ip[i + 1] == 0)
{
if (currentZeroStart == -1)
{
currentZeroStart = i;
}
currentZeroLength += 2;
}
else
{
if (currentZeroLength > longestZeroLength)
{
longestZeroStart = currentZeroStart;
longestZeroLength = currentZeroLength;
}
currentZeroStart = -1;
currentZeroLength = 0;
}
}
if (currentZeroLength > longestZeroLength)
{
longestZeroStart = currentZeroStart;
longestZeroLength = currentZeroLength;
}
// Build the compressed IPv6 address string
var sb = new StringBuilder(ip.Length);
for (var i = 0; i < ip.Length; i += 2)
{
if (i == longestZeroStart)
{
sb.Append(COLON);
i += longestZeroLength - 2;
}
else
{
if (ip[i] == 0 && ip[i + 1] == 0)
{
sb.Append(ZERO);
}
else if (ip[i] == 0)
{
sb.Append(ip[i + 1].ToString(FORMAT_HEX));
}
else
{
sb.Append(ip[i].ToString(FORMAT_HEX));
sb.Append(ip[i + 1].ToString(FORMAT_2HEX));
}
if (i < ip.Length - 2)
sb.Append(COLON);
}
}
return sb.ToString();
}