Jump to content

Canonicalize CIDR: Difference between revisions

→‎{{header|Raku}}: Alternate entry
(Added C++ solution)
(→‎{{header|Raku}}: Alternate entry)
Line 356:
 
=={{header|Raku}}==
===String manipulation===
{{trans|Perl}}
<lang perl6>#!/usr/bin/env raku
Line 385 ⟶ 386:
<pre>$ canonicalize_cidr.raku 87.70.141.1/22
87.70.140.0/22</pre>
 
===Bit mask and shift===
<lang perl6># canonicalize a IP4 CIDR block
sub CIDR-IP4-canonicalize ($address) {
constant @mask = 24, 16, 8, 0;
 
# dotted-decimal / subnet size
my ($dotted, $size) = |$address.split('/'), 32;
 
# get IP as binary address
my $binary = sum $dotted.comb(/\d+/) Z+< @mask;
 
# mask off subnet
$binary +&= (2 ** $size - 1) +< (32 - $size);
 
# Return dotted-decimal notation
(@mask.map($binary +> * +& 0xFF).join('.'), $size)
}
 
my @tests = <
87.70.141.1/22
100.68.0.18/18
10.4.30.77/30
10.207.219.251/32
10.207.219.251
110.200.21/4
10.11.12.13/8
10.../8
>;
 
printf "CIDR: %18s Routing prefix: %s/%s\n", $_, |.&CIDR-IP4-canonicalize
for @*ARGS || @tests».trim;</lang>
{{out}}
<pre>CIDR: 87.70.141.1/22 Routing prefix: 87.70.140.0/22
CIDR: 100.68.0.18/18 Routing prefix: 100.68.0.0/18
CIDR: 10.4.30.77/30 Routing prefix: 10.4.30.76/30
CIDR: 10.207.219.251/32 Routing prefix: 10.207.219.251/32
CIDR: 10.207.219.251 Routing prefix: 10.207.219.251/32
CIDR: 110.200.21/4 Routing prefix: 96.0.0.0/4
CIDR: 10.11.12.13/8 Routing prefix: 10.0.0.0/8
CIDR: 10.../8 Routing prefix: 10.0.0.0/8</pre>
 
=={{header|REXX}}==
10,339

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.