Date: Thu, 6 Jun 2002 23:43:26 -0600 (MDT) From: Warren Block <wblock@wonkity.com> To: BSD Freak <bsd-freak@mbox.com.au> Cc: FreeBSD Questions <freebsd-questions@FreeBSD.ORG> Subject: Re: Converting decimal dotted subnet mask to CIDR in a script Message-ID: <Pine.BSF.4.21.0206062337160.76838-100000@wonkity.com> In-Reply-To: <f9079af91739.f91739f9079a@mbox.com.au>
index | next in thread | previous in thread | raw e-mail
On Fri, 7 Jun 2002, BSD Freak wrote:
> I have a variable in a script we use
>
> $MASK=255.255.255.0
>
> Is there a utility or an easy way to process $MASK and get
>
> $MASKCIDR=24
>
> the CIDR value of 255.255.255.0
Okay:
#!/usr/bin/perl -w
($byte1, $byte2, $byte3, $byte4) = split(/\./, $ARGV[0].".0.0.0.0");
$num = ($byte1 * 16777216) + ($byte2 * 65536) + ($byte3 * 256) + $byte4;
$bin = unpack("B*", pack("N", $num));
$count = ($bin =~ tr/1/1/);
print "$bin = $count bits\n";
The first line is fluff to allow command-line operation. The second
line converts dotted quad to plain decimal. The third line converts
decimal to a binary string. Line four counts the set bits.
However, no test is made on the validity of the mask--the bits should be
contiguous from the left. I'm pretty sure there's an easy regular
expression which would do that, but it's getting late.
-Warren Block * Rapid City, South Dakota USA
To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message
help
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.BSF.4.21.0206062337160.76838-100000>
