Mikrotik Scripting – Function to Split an IP Address into an Array

If you are unfamiliar with Mikrotik networking equipment, do yourself a favor and check them out at mikrotik.com or routerboard.com. Mikrotik uses Router OS, a Linux based operating system. In my eyes, they are every bit as comparable to Cisco at a fraction of the price with an impressive and robust GUI. I’ve been using them in production environments for six years with outstanding results. What other networking equipment has it’s own scripting language? None that I know of. The CCR series of routers with up to 36 processor cores are unparalleled in performance and flexibility.

Here is a function I wrote to be able to split an IP Address into an array of octets or to return just one specific octet.

# Usage: [$returnOctet <ip> <octet number (0-4)>]
# Input an IP Address and 0-3 argument to return a specific octet number or input a 4 to return all octets as an array
:global returnOctet do={
    :if ($1="") do={ :error "You did not specify an IP Address."; }
    :if ($2="") do={ :error "You did not specify an octet to return."; }
    :if (($2>"4") || ($2<"0")) do={ :error "Octet argument out of range."; }
    :local decimalPos "0";
    :local octet1;
    :local octet2;
    :local octet3;
    :local octet4;
    :local octetArray; 
    :set decimalPos [:find $1 "."];
    :set octet1 [:pick $1 0 $decimalPos];
    :set decimalPos ($decimalPos+1);
    :set octet2  [:pick $1 $decimalPos [:find $1 "." $decimalPos]];
    :set decimalPos ([:find $1 "." $decimalPos]+1);
    :set octet3  [:pick $1 $decimalPos [:find $1 "." $decimalPos]];
    :set decimalPos ([:find $1 "." $decimalPos]+1);
    :set octet4 [:pick $1 $decimalPos [:len $1]];
    :set octetArray [:toarray "$octet1,$octet2,$octet3,$octet4"];
    :if (($octet1<"0" || $octet1>"255") || ($octet2<"0" || $octet2>"255") || ($octet3<"0" || $octet3>"255") || ($octet4<"0" || $octet4>"255")) do={ :error "Octet out of range."; }
    :if ($2="0") do={ :return $octet1; }
    :if ($2="1") do={ :return $octet2; }
    :if ($2="2") do={ :return $octet3; }
    :if ($2="3") do={ :return $octet4; }
    :if ($2="4") do={ :return $octetArray; }

Leave a Reply