:global sqrtbin do={ :local count 0
:local value $1
:do {
:set count ($count + 1)
:set value ($value / 2)
} while=($value > 0)
:return $count
}
:global addNatRules do={
:global sqrtbin;
:local toAddrCount $toAddr;
:local x (1<<(([$sqrtbin ($count)])/2));
:local y ($count / $x);
:for j from=$srcStartOct1 to=$srcStopOct1 do={
:for k from=$srcStartOct2 to=$srcStopOct2 do={
:for l from=$srcStartOct3 to=$srcStopOct3 do={
/ip firewall nat add chain=srcnat action=jump jump-target="CGNAT-$($toAddrCount)" \
src-address=(($j.".".$k.".".$l.".".$srcStartOct4)."-".($j.".".$k.".".$l.".".$srcStopOct4)) \
comment="CGNAT" out-interface=LINK
:set toAddrCount ($toAddrCount + 1)
}
}
}
:set toAddrCount $toAddr;
:for j from=$srcStartOct1 to=$srcStopOct1 do={
:for k from=$srcStartOct2 to=$srcStopOct2 do={
:for l from=$srcStartOct3 to=$srcStopOct3 do={
:if ($x * $x = $count) do={ :set y ($x + 1) }
:for i from=0 to=($y-1) do={
:local inicio [:toip (($j.".".$k.".".$l.".".$srcStartOct4) + ($x * $i))]
:local fim [:toip (($j.".".$k.".".$l.".".$srcStartOct4) + ($x * ($i + 1) - 1))]
/ip firewall nat add chain="CGNAT-$($toAddrCount)" action=jump jump-target="CGNAT-$($toAddrCount)-$($i)" \
src-address=([:tostr $inicio]."-".[:tostr $fim]) comment="CGNAT"
}
:set toAddrCount ($toAddrCount + 1)
}
}
}
:set toAddrCount $toAddr
:for j from=$srcStartOct1 to=$srcStopOct1 do={
:for k from=$srcStartOct2 to=$srcStopOct2 do={
:for l from=$srcStartOct3 to=$srcStopOct3 do={
:local srcStart [:toip (($j.".".$k.".".$l.".".$srcStartOct4))]
:for i from=0 to=($count - 1) do={
:local prange "$($portStart + ($i * $portsPerAddr))-$($portStart + (($i + 1) * $portsPerAddr) - 1)"
/ip firewall nat add chain="CGNAT-$($toAddrCount)-$($i / $x)" action=src-nat protocol=tcp src-address=($srcStart + $i) \
to-address=$toAddrCount to-ports=$prange comment="CGNAT"
/ip firewall nat add chain="CGNAT-$($toAddrCount)-$($i / $x)" action=src-nat protocol=udp src-address=($srcStart + $i) \
to-address=$toAddrCount to-ports=$prange comment="CGNAT"
}
:set toAddrCount ($toAddrCount + 1)
}
}
}
}
$addNatRules count=128 srcStartOct1=10 srcStartOct2=150 srcStartOct3=1 srcStartOct4=0 \
srcStopOct1=10 srcStopOct2=150 srcStopOct3=1 srcStopOct4=127 \
toAddr=138.aa.bb.0 portStart=1500 portsPerAddr=500