Canonicalize CIDR: Difference between revisions
m
syntax highlighting fixup automation
(Solution using Python standard library) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 31:
{{trans|C}}
<
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)))</
{{out}}
Line 76:
=={{header|ALGOL 68}}==
<
# mode to hold an IPv4 address in CIDR notation #
MODE CIDR = STRUCT( BITS address
Line 196:
FI
OD
END</
{{out}}
<pre>
Line 209:
=={{header|APL}}==
{{works with|Dyalog APL}}
<
nums←(2⊃⎕VFI)¨(~⍵∊'./')⊆⍵
ip len←(4↑nums)(5⊃nums)
Line 216:
ip←(4/256)⊤2⊥ip
(1↓∊'.',¨⍕¨ip),'/',⍕len
}</
{{out}}
<
87.70.140.0/22</
=={{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.
<
#include <stdio.h>
#include <stdint.h>
Line 287:
}
return 0;
}</
{{out}}
Line 300:
=={{header|C++}}==
<
#include <iomanip>
#include <iostream>
Line 377:
}
return 0;
}</
{{out}}
Line 390:
=={{header|C sharp|C#}}==
<
using System.Net;
using System.Linq;
Line 452:
public override string ToString() => $"{ip}/{length}";
}</
{{out}}
<pre>
Line 463:
=={{header|Commodore BASIC}}==
<
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</
{{Out}}<pre>READY.
Line 521:
READY.</pre>
=={{header|Common Lisp}}==
<
(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>
{{out}}
<pre>
Line 565:
=={{header|Cowgol}}==
<
typedef IP is uint32;
Line 646:
print(" After canonicalization: ");
print(string);
print_nl();</
{{out}}
<pre>Before canonicalization: 87.70.141.1/22
Line 654:
{{trans|Ruby}}
{{works with|Factor|0.99 2020-07-03}}
<
namespaces prettyprint sequences splitting ;
IN: rosetta-code.canonicalize-cidr
Line 675:
! and output
"%s/%d\n" printf
] each</
{{out}}
<pre>
Line 684:
=={{header|Go}}==
{{trans|Ruby}}
<
import (
Line 744:
fmt.Printf("%-18s -> %s\n", test, canonicalize(test))
}
}</
{{out}}
Line 757:
=={{header|Hare}}==
<
use net::ip;
use strings;
Line 800:
0xff & result,
strings::cut(a, "/").1);
};</
{{out}}
<pre>
Line 813:
=={{header|Haskell}}==
This is implemented using only libraries found in the base package.
<
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</
{{out}}
Line 909:
Implementation:
<
'a e'=. 0 ".each (y rplc'. ')-.&;:'/'
('/',":e),~rplc&' .'":_8#.\32{.e{.,(8#2)#:a
}}</
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:
<
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</
=={{header|Java}}==
<
import java.text.ParseException;
Line 997:
"184.232.176.184/18"
};
}</
{{out}}
Line 1,010:
=={{header|JavaScript}}==
<
// Prepare a DataView over a 16 Byte Array buffer.
Line 1,059:
'10..55/8',
'10.../8'
].forEach(test)</
{{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.
<
function canonCIDR(cidr::String)
Line 1,096:
println(canonCIDR("10..55/8"))
println(canonCIDR("10.../8"))
</
<pre>
87.70.140.0/22
Line 1,110:
=={{header|Lua}}==
{{libheader|inet}}
<
test_cases = {
Line 1,119:
for i, cidr in ipairs(test_cases) do
print( inet(cidr):network() )
end</
{{Out}}
Line 1,130:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
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"]</
{{out}}
<pre>87.70.140.0/22
Line 1,168:
=={{header|Nim}}==
Using the IpAddress type from standard module “net”.
<
import strutils
Line 1,224:
# Canonicalize the address and display the result.
ipAddress.canonicalize(nbits)
echo &"{address:<18} ⇢ {ipAddress}/{nbits}"</
{{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.
<
use v5.16;
use Socket qw(inet_aton inet_ntoa);
Line 1,261:
# And output
say "$dotted/$size";
}</
{{Out}}
<pre>$ canonicalize_cidr.pl 87.70.141.1/22
Line 1,267:
=={{header|Phix}}==
<!--<
<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 -> %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>
<!--</
{{out}}
<pre>
Line 1,313:
=={{header|PicoLisp}}==
<
(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)) ) )</
{{out}}
<pre>
Line 1,353:
=={{header|Python}}==
{{trans|Perl}}
<
# 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</
{{Out}}
<pre>$ canonicalize_cidr.py 87.70.141.1/22
Line 1,386:
===Bit mask and shift===
<
DIGITS = (24, 16, 8, 0)
Line 1,424:
print(f"{ip:<18} -> {rv}")
assert rv == expect
</syntaxhighlight>
{{out}}
Line 1,439:
The <code>ipaddress</code> module was added in Python version 3.3.
<
def canonicalize(address: str) -> str:
Line 1,457:
print(f"{ip:<18} -> {rv}")
assert rv == expect, expect
</syntaxhighlight>
{{out}}
Line 1,471:
===Using library===
{{libheader|raku-IP-Addr}}
<syntaxhighlight lang=raku
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)";
}</
===String manipulation===
{{trans|Perl}}
<syntaxhighlight lang=raku
unit sub MAIN(*@cidrs);
Line 1,506:
# And output
say "$canon/$size";
}</
{{Out}}
Line 1,517:
===Bit mask and shift===
<syntaxhighlight lang=raku
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;</
{{out}}
<pre>CIDR: 87.70.141.1/22 Routing prefix: 87.70.140.0/22
Line 1,568:
=={{header|REXX}}==
<
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 " */</
{{out|output|text= when using the default input:}}
<pre>
Line 1,625:
{{trans|Raku}}
<
# canonicalize a CIDR block: make sure none of the host bits are set
Line 1,649:
# And output
puts "#{canon}/#{size}"
end</
{{Out}}
Line 1,655:
87.70.140.0/22</pre>
===Built in===
<
require "ipaddr"
Line 1,665:
puts "#{ia}/#{ia.prefix}"
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,676:
=={{header|Rust}}==
<
fn canonical_cidr(cidr: &str) -> Result<String, &str> {
Line 1,714:
fn main() {
println!("{}", canonical_cidr("127.1.2.3/24").unwrap());
}</
=={{header|SNOBOL}}==
<
D = SPAN('0123456789')
Line 1,764:
OUTPUT = FIXCIDR('161.214.74.21/24')
OUTPUT = FIXCIDR('184.232.176.184/18')
END</
{{Out}}
Line 1,778:
{{works with|Korn Shell}}
{{works with|Zsh}}
<
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 "$@"</
{{Out}}
<pre>36.16.0.0/12
Line 1,834:
{{libheader|Wren-fmt}}
{{libheader|Wren-str}}
<
import "/str" for Str
Line 1,869:
for (test in tests) {
Fmt.print("$-18s -> $s", test, canonicalize.call(test))
}</
{{out}}
|