Jump to content

Canonicalize CIDR: Difference between revisions

m
syntax highlighting fixup automation
(Solution using Python standard library)
m (syntax highlighting fixup automation)
Line 31:
{{trans|C}}
 
<langsyntaxhighlight lang=11l>F cidr_parse(str)
V (addr_str, m_str) = str.split(‘/’)
V (a, b, c, d) = addr_str.split(‘.’).map(Int)
Line 63:
‘184.232.176.184/18’]
V (address, mask_length) = cidr_parse(test)
print(‘#<18 -> #.’.format(test, cidr_format(address, mask_length)))</langsyntaxhighlight>
 
{{out}}
Line 76:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang=algol68>BEGIN # show IPv4 addresses in CIDR notation in canonical form #
# mode to hold an IPv4 address in CIDR notation #
MODE CIDR = STRUCT( BITS address
Line 196:
FI
OD
END</langsyntaxhighlight>
{{out}}
<pre>
Line 209:
=={{header|APL}}==
{{works with|Dyalog APL}}
<langsyntaxhighlight lang=apl> canonicalize←{
nums←(2⊃⎕VFI)¨(~⍵∊'./')⊆⍵
ip len←(4↑nums)(5⊃nums)
Line 216:
ip←(4/256)⊤2⊥ip
(1↓∊'.',¨⍕¨ip),'/',⍕len
}</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang=apl> canonicalize '87.70.141.1/22'
87.70.140.0/22</langsyntaxhighlight>
 
=={{header|C}}==
This solution uses only the standard library. On POSIX platforms one can use the functions
inet_pton/inet_ntop to parse/format IPv4 addresses.
<langsyntaxhighlight lang=c>#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
Line 287:
}
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 300:
 
=={{header|C++}}==
<langsyntaxhighlight lang=cpp>#include <cstdint>
#include <iomanip>
#include <iostream>
Line 377:
}
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 390:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang=csharp>using System;
using System.Net;
using System.Linq;
Line 452:
public override string ToString() => $"{ip}/{length}";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 463:
 
=={{header|Commodore BASIC}}==
<langsyntaxhighlight lang=gwbasic>100 REM THE BINARY OPS ONLY WORK ON SIGNED 16-BIT NUMBERS
110 REM SO WE STORE THE IP ADDRESS AS AN ARRAY OF FOUR OCTETS
120 DIM IP(3)
Line 504:
520 REM SOME INVALID INPUTS
530 DATA 127.0.0.1, 123.45.67.89/0, 98.76.54.32/100, 123.456.789.0/12
540 DATA</langsyntaxhighlight>
 
{{Out}}<pre>READY.
Line 521:
READY.</pre>
=={{header|Common Lisp}}==
<langsyntaxhighlight lang=lisp>(defun ip->bit-vector (ip)
(flet ((int->bits (int)
(loop :for i :below 8
Line 555:
:for ccidr := (canonicalize-cidr cidr)
:do (format t "~&~A~20,T→ ~A~%" cidr ccidr))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 565:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang=cowgol>include "cowgol.coh";
 
typedef IP is uint32;
Line 646:
print(" After canonicalization: ");
print(string);
print_nl();</langsyntaxhighlight>
{{out}}
<pre>Before canonicalization: 87.70.141.1/22
Line 654:
{{trans|Ruby}}
{{works with|Factor|0.99 2020-07-03}}
<langsyntaxhighlight lang=factor>USING: command-line formatting grouping io kernel math.parser
namespaces prettyprint sequences splitting ;
IN: rosetta-code.canonicalize-cidr
Line 675:
! and output
"%s/%d\n" printf
] each</langsyntaxhighlight>
{{out}}
<pre>
Line 684:
=={{header|Go}}==
{{trans|Ruby}}
<langsyntaxhighlight lang=go>package main
 
import (
Line 744:
fmt.Printf("%-18s -> %s\n", test, canonicalize(test))
}
}</langsyntaxhighlight>
 
{{out}}
Line 757:
 
=={{header|Hare}}==
<langsyntaxhighlight lang=hare>use fmt;
use net::ip;
use strings;
Line 800:
0xff & result,
strings::cut(a, "/").1);
};</langsyntaxhighlight>
{{out}}
<pre>
Line 813:
=={{header|Haskell}}==
This is implemented using only libraries found in the base package.
<langsyntaxhighlight lang=haskell>import Control.Monad (guard)
import Data.Bits ((.|.), (.&.), complement, shiftL, shiftR, zeroBits)
import Data.Maybe (listToMaybe)
Line 890:
test "184.256.176.184/12" -- octet value is too large
test "184.232.176.184/33" -- netmask size is too large
test "184.232.184/18" -- too few components</langsyntaxhighlight>
 
{{out}}
Line 909:
Implementation:
 
<langsyntaxhighlight lang=J>cidr=: {{
'a e'=. 0 ".each (y rplc'. ')-.&;:'/'
('/',":e),~rplc&' .'":_8#.\32{.e{.,(8#2)#:a
}}</langsyntaxhighlight>
 
In other words, convert address part to bits, truncate to the network address, extend back to 32 bits and repack into the ascii representation.
Line 918:
Task examples:
 
<langsyntaxhighlight lang=J> cidr '87.70.141.1/22'
87.70.140.0/22
cidr '36.18.154.103/12'
Line 929:
161.214.74.0/24
cidr '184.232.176.184/18'
184.232.128.0/18</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang=java>import java.text.MessageFormat;
import java.text.ParseException;
 
Line 997:
"184.232.176.184/18"
};
}</langsyntaxhighlight>
 
{{out}}
Line 1,010:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang=javascript>const canonicalize = s => {
 
// Prepare a DataView over a 16 Byte Array buffer.
Line 1,059:
'10..55/8',
'10.../8'
].forEach(test)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,077:
=={{header|Julia}}==
Julia has a Sockets library as a builtin, which has the types IPv4 and IPv6 for single IP addresses.
<langsyntaxhighlight lang=julia>using Sockets
 
function canonCIDR(cidr::String)
Line 1,096:
println(canonCIDR("10..55/8"))
println(canonCIDR("10.../8"))
</langsyntaxhighlight>{{out}}
<pre>
87.70.140.0/22
Line 1,110:
=={{header|Lua}}==
{{libheader|inet}}
<langsyntaxhighlight lang=lua>inet = require 'inet'
 
test_cases = {
Line 1,119:
for i, cidr in ipairs(test_cases) do
print( inet(cidr):network() )
end</langsyntaxhighlight>
 
{{Out}}
Line 1,130:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang=Mathematica>ClearAll[CanonicalizeCIDR]
CanonicalizeCIDR[str_String] := Module[{i, ip, chop, keep, change},
If[StringMatchQ[str, "*.*.*.*/*"],
Line 1,157:
CanonicalizeCIDR["67.137.119.181/4"]
CanonicalizeCIDR["161.214.74.21/24"]
CanonicalizeCIDR["184.232.176.184/18"]</langsyntaxhighlight>
{{out}}
<pre>87.70.140.0/22
Line 1,168:
=={{header|Nim}}==
Using the IpAddress type from standard module “net”.
<langsyntaxhighlight lang=Nim>import net
import strutils
 
Line 1,224:
# Canonicalize the address and display the result.
ipAddress.canonicalize(nbits)
echo &"{address:<18} ⇢ {ipAddress}/{nbits}"</langsyntaxhighlight>
 
{{out}}
Line 1,236:
=={{header|Perl}}==
There's a CPAN module for IP address manipulation, <tt>Net::IP</tt>. Unfortunately, it requires a CIDR string to be already in canonical form; otherwise it fails with an "Invalid prefix" error. So we do it manually.
<langsyntaxhighlight lang=perl>#!/usr/bin/env perl
use v5.16;
use Socket qw(inet_aton inet_ntoa);
Line 1,261:
# And output
say "$dotted/$size";
}</langsyntaxhighlight>
{{Out}}
<pre>$ canonicalize_cidr.pl 87.70.141.1/22
Line 1,267:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> <span style="color: #000080;font-style:italic;">-- (not likely useful)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">canonicalize_cidr</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">cidr</span><span style="color: #0000FF;">)</span>
Line 1,301:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%-18s -&gt; %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">,</span><span style="color: #000000;">canonicalize_cidr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,313:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(de cidr (S)
(let
(L (rot (mapcar format (split (chop S) "." "/")))
Line 1,340:
"161.214.74.21/24"
"184.232.176.184/18" )
(tab Fmt A "=>" (cidr A)) ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 1,353:
=={{header|Python}}==
{{trans|Perl}}
<langsyntaxhighlight lang=python>#!/usr/bin/env python
# canonicalize a CIDR block specification:
# make sure none of the host bits are set
Line 1,380:
canon_dotted = inet_ntoa(pack('!I',
(canon_numeric))) # and then to dotted-decimal
print(f'{canon_dotted}/{size}') # output result</langsyntaxhighlight>
{{Out}}
<pre>$ canonicalize_cidr.py 87.70.141.1/22
Line 1,386:
 
===Bit mask and shift===
<langsyntaxhighlight lang=python>"""Canonicalize CIDR"""
DIGITS = (24, 16, 8, 0)
 
Line 1,424:
print(f"{ip:<18} -> {rv}")
assert rv == expect
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,439:
The <code>ipaddress</code> module was added in Python version 3.3.
 
<langsyntaxhighlight lang=python>import ipaddress
 
def canonicalize(address: str) -> str:
Line 1,457:
print(f"{ip:<18} -> {rv}")
assert rv == expect, expect
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,471:
===Using library===
{{libheader|raku-IP-Addr}}
<syntaxhighlight lang=raku perl6line>use IP::Addr;
for «87.70.141.1/22 36.18.154.103/12 62.62.197.11/29 67.137.119.181/4 161.214.74.21/24 184.232.176.184/18» -> $cidr {
say "$cidr -> $(IP::Addr.new($cidr).network)";
}</langsyntaxhighlight>
 
===String manipulation===
{{trans|Perl}}
<syntaxhighlight lang=raku perl6line>#!/usr/bin/env raku
unit sub MAIN(*@cidrs);
 
Line 1,506:
# And output
say "$canon/$size";
}</langsyntaxhighlight>
 
{{Out}}
Line 1,517:
 
===Bit mask and shift===
<syntaxhighlight lang=raku perl6line># canonicalize a IP4 CIDR block
sub CIDR-IP4-canonicalize ($address) {
constant @mask = 24, 16, 8, 0;
Line 1,551:
printf "CIDR: %18s Routing prefix: %s/%s\n", $_, |.&CIDR-IP4-canonicalize
for @*ARGS || @tests;</langsyntaxhighlight>
{{out}}
<pre>CIDR: 87.70.141.1/22 Routing prefix: 87.70.140.0/22
Line 1,568:
 
=={{header|REXX}}==
<langsyntaxhighlight lang=rexx>/*REXX pgm canonicalizes IPv4 addresses that are in CIDR notation (dotted─dec/network).*/
parse arg a . /*obtain optional argument from the CL.*/
if a=='' | a=="," then a= '87.70.141.1/22' , /*Not specified? Then use the defaults*/
Line 1,599:
/*──────────────────────────────────────────────────────────────────────────────────────*/
b2d: return x2d( b2x( arg(1) ) ) + 0 /*convert binary ───► decimal number.*/
d2b: return x2b( d2x( arg(1) ) ) + 0 /* " decimal ───► binary " */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 1,625:
{{trans|Raku}}
 
<langsyntaxhighlight lang=ruby>#!/usr/bin/env ruby
 
# canonicalize a CIDR block: make sure none of the host bits are set
Line 1,649:
# And output
puts "#{canon}/#{size}"
end</langsyntaxhighlight>
 
{{Out}}
Line 1,655:
87.70.140.0/22</pre>
===Built in===
<langsyntaxhighlight lang=ruby>
require "ipaddr"
Line 1,665:
puts "#{ia}/#{ia.prefix}"
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,676:
 
=={{header|Rust}}==
<langsyntaxhighlight lang=Rust>use std::net::Ipv4Addr;
 
fn canonical_cidr(cidr: &str) -> Result<String, &str> {
Line 1,714:
fn main() {
println!("{}", canonical_cidr("127.1.2.3/24").unwrap());
}</langsyntaxhighlight>
 
=={{header|SNOBOL}}==
<langsyntaxhighlight lang=snobol>* Pattern to match any number of digits
D = SPAN('0123456789')
 
Line 1,764:
OUTPUT = FIXCIDR('161.214.74.21/24')
OUTPUT = FIXCIDR('184.232.176.184/18')
END</langsyntaxhighlight>
 
{{Out}}
Line 1,778:
{{works with|Korn Shell}}
{{works with|Zsh}}
<langsyntaxhighlight lang=bash>function inet_aton {
typeset -i addr byte
typeset -a bytes
Line 1,822:
set -- 36.18.154.103/12 62.62.197.11/29 67.137.119.181/4 161.214.74.21/24 184.232.176.184/18
fi
canonicalize_cidr "$@"</langsyntaxhighlight>
{{Out}}
<pre>36.16.0.0/12
Line 1,834:
{{libheader|Wren-fmt}}
{{libheader|Wren-str}}
<langsyntaxhighlight lang=ecmascript>import "/fmt" for Fmt, Conv
import "/str" for Str
 
Line 1,869:
for (test in tests) {
Fmt.print("$-18s -> $s", test, canonicalize.call(test))
}</langsyntaxhighlight>
 
{{out}}
10,333

edits

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