From owner-freebsd-questions Thu Jun 6 22:43:32 2002 Delivered-To: freebsd-questions@freebsd.org Received: from wonkity.com (wonkity.com [63.93.4.4]) by hub.freebsd.org (Postfix) with ESMTP id 5659037B404 for ; Thu, 6 Jun 2002 22:43:27 -0700 (PDT) Received: from wonkity.com (localhost.wonkity.com [127.0.0.1]) by wonkity.com (8.12.1/8.11.6) with ESMTP id g575hQuF076856; Thu, 6 Jun 2002 23:43:26 -0600 (MDT) (envelope-from wblock@wonkity.com) Received: from localhost (wblock@localhost) by wonkity.com (8.12.1/8.12.1/Submit) with ESMTP id g575hQuC076853; Thu, 6 Jun 2002 23:43:26 -0600 (MDT)?g (envelope-from wblock@wonkity.com) Date: Thu, 6 Jun 2002 23:43:26 -0600 (MDT) From: Warren Block To: BSD Freak Cc: FreeBSD Questions Subject: Re: Converting decimal dotted subnet mask to CIDR in a script In-Reply-To: Message-ID: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII Sender: owner-freebsd-questions@FreeBSD.ORG Precedence: bulk List-ID: List-Archive: (Web Archive) List-Help: (List Instructions) List-Subscribe: List-Unsubscribe: X-Loop: FreeBSD.ORG 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