Canonicalize CIDR: Difference between revisions

Content added Content deleted
(Solution using Python standard library)
m (syntax highlighting fixup automation)
Line 31: Line 31:
{{trans|C}}
{{trans|C}}


<lang 11l>F cidr_parse(str)
<syntaxhighlight lang=11l>F cidr_parse(str)
V (addr_str, m_str) = str.split(‘/’)
V (addr_str, m_str) = str.split(‘/’)
V (a, b, c, d) = addr_str.split(‘.’).map(Int)
V (a, b, c, d) = addr_str.split(‘.’).map(Int)
Line 63: Line 63:
‘184.232.176.184/18’]
‘184.232.176.184/18’]
V (address, mask_length) = cidr_parse(test)
V (address, mask_length) = cidr_parse(test)
print(‘#<18 -> #.’.format(test, cidr_format(address, mask_length)))</lang>
print(‘#<18 -> #.’.format(test, cidr_format(address, mask_length)))</syntaxhighlight>


{{out}}
{{out}}
Line 76: Line 76:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>BEGIN # show IPv4 addresses in CIDR notation in canonical form #
<syntaxhighlight lang=algol68>BEGIN # show IPv4 addresses in CIDR notation in canonical form #
# mode to hold an IPv4 address in CIDR notation #
# mode to hold an IPv4 address in CIDR notation #
MODE CIDR = STRUCT( BITS address
MODE CIDR = STRUCT( BITS address
Line 196: Line 196:
FI
FI
OD
OD
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 209: Line 209:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<lang apl> canonicalize←{
<syntaxhighlight lang=apl> canonicalize←{
nums←(2⊃⎕VFI)¨(~⍵∊'./')⊆⍵
nums←(2⊃⎕VFI)¨(~⍵∊'./')⊆⍵
ip len←(4↑nums)(5⊃nums)
ip len←(4↑nums)(5⊃nums)
Line 216: Line 216:
ip←(4/256)⊤2⊥ip
ip←(4/256)⊤2⊥ip
(1↓∊'.',¨⍕¨ip),'/',⍕len
(1↓∊'.',¨⍕¨ip),'/',⍕len
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<lang apl> canonicalize '87.70.141.1/22'
<syntaxhighlight lang=apl> canonicalize '87.70.141.1/22'
87.70.140.0/22</lang>
87.70.140.0/22</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
This solution uses only the standard library. On POSIX platforms one can use the functions
This solution uses only the standard library. On POSIX platforms one can use the functions
inet_pton/inet_ntop to parse/format IPv4 addresses.
inet_pton/inet_ntop to parse/format IPv4 addresses.
<lang c>#include <stdbool.h>
<syntaxhighlight lang=c>#include <stdbool.h>
#include <stdio.h>
#include <stdio.h>
#include <stdint.h>
#include <stdint.h>
Line 287: Line 287:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 300: Line 300:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <cstdint>
<syntaxhighlight lang=cpp>#include <cstdint>
#include <iomanip>
#include <iomanip>
#include <iostream>
#include <iostream>
Line 377: Line 377:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 390: Line 390:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;
using System.Net;
using System.Net;
using System.Linq;
using System.Linq;
Line 452: Line 452:
public override string ToString() => $"{ip}/{length}";
public override string ToString() => $"{ip}/{length}";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 463: Line 463:


=={{header|Commodore BASIC}}==
=={{header|Commodore BASIC}}==
<lang gwbasic>100 REM THE BINARY OPS ONLY WORK ON SIGNED 16-BIT NUMBERS
<syntaxhighlight 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
110 REM SO WE STORE THE IP ADDRESS AS AN ARRAY OF FOUR OCTETS
120 DIM IP(3)
120 DIM IP(3)
Line 504: Line 504:
520 REM SOME INVALID INPUTS
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
530 DATA 127.0.0.1, 123.45.67.89/0, 98.76.54.32/100, 123.456.789.0/12
540 DATA</lang>
540 DATA</syntaxhighlight>


{{Out}}<pre>READY.
{{Out}}<pre>READY.
Line 521: Line 521:
READY.</pre>
READY.</pre>
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun ip->bit-vector (ip)
<syntaxhighlight lang=lisp>(defun ip->bit-vector (ip)
(flet ((int->bits (int)
(flet ((int->bits (int)
(loop :for i :below 8
(loop :for i :below 8
Line 555: Line 555:
:for ccidr := (canonicalize-cidr cidr)
:for ccidr := (canonicalize-cidr cidr)
:do (format t "~&~A~20,T→ ~A~%" cidr ccidr))
:do (format t "~&~A~20,T→ ~A~%" cidr ccidr))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 565: Line 565:


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang=cowgol>include "cowgol.coh";


typedef IP is uint32;
typedef IP is uint32;
Line 646: Line 646:
print(" After canonicalization: ");
print(" After canonicalization: ");
print(string);
print(string);
print_nl();</lang>
print_nl();</syntaxhighlight>
{{out}}
{{out}}
<pre>Before canonicalization: 87.70.141.1/22
<pre>Before canonicalization: 87.70.141.1/22
Line 654: Line 654:
{{trans|Ruby}}
{{trans|Ruby}}
{{works with|Factor|0.99 2020-07-03}}
{{works with|Factor|0.99 2020-07-03}}
<lang factor>USING: command-line formatting grouping io kernel math.parser
<syntaxhighlight lang=factor>USING: command-line formatting grouping io kernel math.parser
namespaces prettyprint sequences splitting ;
namespaces prettyprint sequences splitting ;
IN: rosetta-code.canonicalize-cidr
IN: rosetta-code.canonicalize-cidr
Line 675: Line 675:
! and output
! and output
"%s/%d\n" printf
"%s/%d\n" printf
] each</lang>
] each</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 684: Line 684:
=={{header|Go}}==
=={{header|Go}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 744: Line 744:
fmt.Printf("%-18s -> %s\n", test, canonicalize(test))
fmt.Printf("%-18s -> %s\n", test, canonicalize(test))
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 757: Line 757:


=={{header|Hare}}==
=={{header|Hare}}==
<lang hare>use fmt;
<syntaxhighlight lang=hare>use fmt;
use net::ip;
use net::ip;
use strings;
use strings;
Line 800: Line 800:
0xff & result,
0xff & result,
strings::cut(a, "/").1);
strings::cut(a, "/").1);
};</lang>
};</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 813: Line 813:
=={{header|Haskell}}==
=={{header|Haskell}}==
This is implemented using only libraries found in the base package.
This is implemented using only libraries found in the base package.
<lang haskell>import Control.Monad (guard)
<syntaxhighlight lang=haskell>import Control.Monad (guard)
import Data.Bits ((.|.), (.&.), complement, shiftL, shiftR, zeroBits)
import Data.Bits ((.|.), (.&.), complement, shiftL, shiftR, zeroBits)
import Data.Maybe (listToMaybe)
import Data.Maybe (listToMaybe)
Line 890: Line 890:
test "184.256.176.184/12" -- octet value is too large
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.176.184/33" -- netmask size is too large
test "184.232.184/18" -- too few components</lang>
test "184.232.184/18" -- too few components</syntaxhighlight>


{{out}}
{{out}}
Line 909: Line 909:
Implementation:
Implementation:


<lang J>cidr=: {{
<syntaxhighlight lang=J>cidr=: {{
'a e'=. 0 ".each (y rplc'. ')-.&;:'/'
'a e'=. 0 ".each (y rplc'. ')-.&;:'/'
('/',":e),~rplc&' .'":_8#.\32{.e{.,(8#2)#:a
('/',":e),~rplc&' .'":_8#.\32{.e{.,(8#2)#:a
}}</lang>
}}</syntaxhighlight>


In other words, convert address part to bits, truncate to the network address, extend back to 32 bits and repack into the ascii representation.
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: Line 918:
Task examples:
Task examples:


<lang J> cidr '87.70.141.1/22'
<syntaxhighlight lang=J> cidr '87.70.141.1/22'
87.70.140.0/22
87.70.140.0/22
cidr '36.18.154.103/12'
cidr '36.18.154.103/12'
Line 929: Line 929:
161.214.74.0/24
161.214.74.0/24
cidr '184.232.176.184/18'
cidr '184.232.176.184/18'
184.232.128.0/18</lang>
184.232.128.0/18</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.text.MessageFormat;
<syntaxhighlight lang=java>import java.text.MessageFormat;
import java.text.ParseException;
import java.text.ParseException;


Line 997: Line 997:
"184.232.176.184/18"
"184.232.176.184/18"
};
};
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,010: Line 1,010:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>const canonicalize = s => {
<syntaxhighlight lang=javascript>const canonicalize = s => {


// Prepare a DataView over a 16 Byte Array buffer.
// Prepare a DataView over a 16 Byte Array buffer.
Line 1,059: Line 1,059:
'10..55/8',
'10..55/8',
'10.../8'
'10.../8'
].forEach(test)</lang>
].forEach(test)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,077: Line 1,077:
=={{header|Julia}}==
=={{header|Julia}}==
Julia has a Sockets library as a builtin, which has the types IPv4 and IPv6 for single IP addresses.
Julia has a Sockets library as a builtin, which has the types IPv4 and IPv6 for single IP addresses.
<lang julia>using Sockets
<syntaxhighlight lang=julia>using Sockets


function canonCIDR(cidr::String)
function canonCIDR(cidr::String)
Line 1,096: Line 1,096:
println(canonCIDR("10..55/8"))
println(canonCIDR("10..55/8"))
println(canonCIDR("10.../8"))
println(canonCIDR("10.../8"))
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
87.70.140.0/22
87.70.140.0/22
Line 1,110: Line 1,110:
=={{header|Lua}}==
=={{header|Lua}}==
{{libheader|inet}}
{{libheader|inet}}
<lang lua>inet = require 'inet'
<syntaxhighlight lang=lua>inet = require 'inet'


test_cases = {
test_cases = {
Line 1,119: Line 1,119:
for i, cidr in ipairs(test_cases) do
for i, cidr in ipairs(test_cases) do
print( inet(cidr):network() )
print( inet(cidr):network() )
end</lang>
end</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,130: Line 1,130:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>ClearAll[CanonicalizeCIDR]
<syntaxhighlight lang=Mathematica>ClearAll[CanonicalizeCIDR]
CanonicalizeCIDR[str_String] := Module[{i, ip, chop, keep, change},
CanonicalizeCIDR[str_String] := Module[{i, ip, chop, keep, change},
If[StringMatchQ[str, "*.*.*.*/*"],
If[StringMatchQ[str, "*.*.*.*/*"],
Line 1,157: Line 1,157:
CanonicalizeCIDR["67.137.119.181/4"]
CanonicalizeCIDR["67.137.119.181/4"]
CanonicalizeCIDR["161.214.74.21/24"]
CanonicalizeCIDR["161.214.74.21/24"]
CanonicalizeCIDR["184.232.176.184/18"]</lang>
CanonicalizeCIDR["184.232.176.184/18"]</syntaxhighlight>
{{out}}
{{out}}
<pre>87.70.140.0/22
<pre>87.70.140.0/22
Line 1,168: Line 1,168:
=={{header|Nim}}==
=={{header|Nim}}==
Using the IpAddress type from standard module “net”.
Using the IpAddress type from standard module “net”.
<lang Nim>import net
<syntaxhighlight lang=Nim>import net
import strutils
import strutils


Line 1,224: Line 1,224:
# Canonicalize the address and display the result.
# Canonicalize the address and display the result.
ipAddress.canonicalize(nbits)
ipAddress.canonicalize(nbits)
echo &"{address:<18} ⇢ {ipAddress}/{nbits}"</lang>
echo &"{address:<18} ⇢ {ipAddress}/{nbits}"</syntaxhighlight>


{{out}}
{{out}}
Line 1,236: Line 1,236:
=={{header|Perl}}==
=={{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.
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.
<lang perl>#!/usr/bin/env perl
<syntaxhighlight lang=perl>#!/usr/bin/env perl
use v5.16;
use v5.16;
use Socket qw(inet_aton inet_ntoa);
use Socket qw(inet_aton inet_ntoa);
Line 1,261: Line 1,261:
# And output
# And output
say "$dotted/$size";
say "$dotted/$size";
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>$ canonicalize_cidr.pl 87.70.141.1/22
<pre>$ canonicalize_cidr.pl 87.70.141.1/22
Line 1,267: Line 1,267:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight 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;">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>
<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: 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: #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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,313: Line 1,313:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de cidr (S)
<syntaxhighlight lang=PicoLisp>(de cidr (S)
(let
(let
(L (rot (mapcar format (split (chop S) "." "/")))
(L (rot (mapcar format (split (chop S) "." "/")))
Line 1,340: Line 1,340:
"161.214.74.21/24"
"161.214.74.21/24"
"184.232.176.184/18" )
"184.232.176.184/18" )
(tab Fmt A "=>" (cidr A)) ) )</lang>
(tab Fmt A "=>" (cidr A)) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,353: Line 1,353:
=={{header|Python}}==
=={{header|Python}}==
{{trans|Perl}}
{{trans|Perl}}
<lang python>#!/usr/bin/env python
<syntaxhighlight lang=python>#!/usr/bin/env python
# canonicalize a CIDR block specification:
# canonicalize a CIDR block specification:
# make sure none of the host bits are set
# make sure none of the host bits are set
Line 1,380: Line 1,380:
canon_dotted = inet_ntoa(pack('!I',
canon_dotted = inet_ntoa(pack('!I',
(canon_numeric))) # and then to dotted-decimal
(canon_numeric))) # and then to dotted-decimal
print(f'{canon_dotted}/{size}') # output result</lang>
print(f'{canon_dotted}/{size}') # output result</syntaxhighlight>
{{Out}}
{{Out}}
<pre>$ canonicalize_cidr.py 87.70.141.1/22
<pre>$ canonicalize_cidr.py 87.70.141.1/22
Line 1,386: Line 1,386:


===Bit mask and shift===
===Bit mask and shift===
<lang python>"""Canonicalize CIDR"""
<syntaxhighlight lang=python>"""Canonicalize CIDR"""
DIGITS = (24, 16, 8, 0)
DIGITS = (24, 16, 8, 0)


Line 1,424: Line 1,424:
print(f"{ip:<18} -> {rv}")
print(f"{ip:<18} -> {rv}")
assert rv == expect
assert rv == expect
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,439: Line 1,439:
The <code>ipaddress</code> module was added in Python version 3.3.
The <code>ipaddress</code> module was added in Python version 3.3.


<lang python>import ipaddress
<syntaxhighlight lang=python>import ipaddress


def canonicalize(address: str) -> str:
def canonicalize(address: str) -> str:
Line 1,457: Line 1,457:
print(f"{ip:<18} -> {rv}")
print(f"{ip:<18} -> {rv}")
assert rv == expect, expect
assert rv == expect, expect
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,471: Line 1,471:
===Using library===
===Using library===
{{libheader|raku-IP-Addr}}
{{libheader|raku-IP-Addr}}
<lang perl6>use IP::Addr;
<syntaxhighlight lang=raku line>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 {
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)";
say "$cidr -> $(IP::Addr.new($cidr).network)";
}</lang>
}</syntaxhighlight>


===String manipulation===
===String manipulation===
{{trans|Perl}}
{{trans|Perl}}
<lang perl6>#!/usr/bin/env raku
<syntaxhighlight lang=raku line>#!/usr/bin/env raku
unit sub MAIN(*@cidrs);
unit sub MAIN(*@cidrs);


Line 1,506: Line 1,506:
# And output
# And output
say "$canon/$size";
say "$canon/$size";
}</lang>
}</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,517: Line 1,517:


===Bit mask and shift===
===Bit mask and shift===
<lang perl6># canonicalize a IP4 CIDR block
<syntaxhighlight lang=raku line># canonicalize a IP4 CIDR block
sub CIDR-IP4-canonicalize ($address) {
sub CIDR-IP4-canonicalize ($address) {
constant @mask = 24, 16, 8, 0;
constant @mask = 24, 16, 8, 0;
Line 1,551: Line 1,551:
printf "CIDR: %18s Routing prefix: %s/%s\n", $_, |.&CIDR-IP4-canonicalize
printf "CIDR: %18s Routing prefix: %s/%s\n", $_, |.&CIDR-IP4-canonicalize
for @*ARGS || @tests;</lang>
for @*ARGS || @tests;</syntaxhighlight>
{{out}}
{{out}}
<pre>CIDR: 87.70.141.1/22 Routing prefix: 87.70.140.0/22
<pre>CIDR: 87.70.141.1/22 Routing prefix: 87.70.140.0/22
Line 1,568: Line 1,568:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX pgm canonicalizes IPv4 addresses that are in CIDR notation (dotted─dec/network).*/
<syntaxhighlight lang=rexx>/*REXX pgm canonicalizes IPv4 addresses that are in CIDR notation (dotted─dec/network).*/
parse arg a . /*obtain optional argument from the CL.*/
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*/
if a=='' | a=="," then a= '87.70.141.1/22' , /*Not specified? Then use the defaults*/
Line 1,599: Line 1,599:
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
b2d: return x2d( b2x( arg(1) ) ) + 0 /*convert binary ───► decimal number.*/
b2d: return x2d( b2x( arg(1) ) ) + 0 /*convert binary ───► decimal number.*/
d2b: return x2b( d2x( arg(1) ) ) + 0 /* " decimal ───► binary " */</lang>
d2b: return x2b( d2x( arg(1) ) ) + 0 /* " decimal ───► binary " */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 1,625: Line 1,625:
{{trans|Raku}}
{{trans|Raku}}


<lang ruby>#!/usr/bin/env ruby
<syntaxhighlight lang=ruby>#!/usr/bin/env ruby


# canonicalize a CIDR block: make sure none of the host bits are set
# canonicalize a CIDR block: make sure none of the host bits are set
Line 1,649: Line 1,649:
# And output
# And output
puts "#{canon}/#{size}"
puts "#{canon}/#{size}"
end</lang>
end</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,655: Line 1,655:
87.70.140.0/22</pre>
87.70.140.0/22</pre>
===Built in===
===Built in===
<lang ruby>
<syntaxhighlight lang=ruby>
require "ipaddr"
require "ipaddr"
Line 1,665: Line 1,665:
puts "#{ia}/#{ia.prefix}"
puts "#{ia}/#{ia.prefix}"
end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,676: Line 1,676:


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>use std::net::Ipv4Addr;
<syntaxhighlight lang=Rust>use std::net::Ipv4Addr;


fn canonical_cidr(cidr: &str) -> Result<String, &str> {
fn canonical_cidr(cidr: &str) -> Result<String, &str> {
Line 1,714: Line 1,714:
fn main() {
fn main() {
println!("{}", canonical_cidr("127.1.2.3/24").unwrap());
println!("{}", canonical_cidr("127.1.2.3/24").unwrap());
}</lang>
}</syntaxhighlight>


=={{header|SNOBOL}}==
=={{header|SNOBOL}}==
<lang snobol>* Pattern to match any number of digits
<syntaxhighlight lang=snobol>* Pattern to match any number of digits
D = SPAN('0123456789')
D = SPAN('0123456789')


Line 1,764: Line 1,764:
OUTPUT = FIXCIDR('161.214.74.21/24')
OUTPUT = FIXCIDR('161.214.74.21/24')
OUTPUT = FIXCIDR('184.232.176.184/18')
OUTPUT = FIXCIDR('184.232.176.184/18')
END</lang>
END</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,778: Line 1,778:
{{works with|Korn Shell}}
{{works with|Korn Shell}}
{{works with|Zsh}}
{{works with|Zsh}}
<lang bash>function inet_aton {
<syntaxhighlight lang=bash>function inet_aton {
typeset -i addr byte
typeset -i addr byte
typeset -a bytes
typeset -a bytes
Line 1,822: 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
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
fi
canonicalize_cidr "$@"</lang>
canonicalize_cidr "$@"</syntaxhighlight>
{{Out}}
{{Out}}
<pre>36.16.0.0/12
<pre>36.16.0.0/12
Line 1,834: Line 1,834:
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
{{libheader|Wren-str}}
{{libheader|Wren-str}}
<lang ecmascript>import "/fmt" for Fmt, Conv
<syntaxhighlight lang=ecmascript>import "/fmt" for Fmt, Conv
import "/str" for Str
import "/str" for Str


Line 1,869: Line 1,869:
for (test in tests) {
for (test in tests) {
Fmt.print("$-18s -> $s", test, canonicalize.call(test))
Fmt.print("$-18s -> $s", test, canonicalize.call(test))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}