init
Some checks are pending
CI / build (push) Waiting to run
CI / deploy (push) Blocked by required conditions

This commit is contained in:
ge
2025-04-05 22:49:43 +03:00
commit ef87b21308
21 changed files with 4262 additions and 0 deletions

134
src/128bit_math.v Normal file
View File

@ -0,0 +1,134 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
/*
This file contains functions for operating with big endian ordered byte arrays.
Using big.Integer is significantly slower than doing math strictly on 128-bit
numbers. At a minimum, you have to do expensive instantiation of big.Integer.
The functions below do not require copying arrays and allocate less memory.
Functions missing:
fn add_128(a [16]u8, b [16]u8) [16]u8
fn diff_128(a [16]u8, b [16]u8) [16]u8
*/
module netaddr
import math.bits
const max_128 = [16]u8{init: 0xff}
@[direct_array_access; inline]
fn bit_len_128(a [16]u8) int {
if a == [16]u8{} {
return 0
}
mut len := 128
mut zeros := 0
for i in 0 .. 16 {
zeros = bits.leading_zeros_8(a[i])
if zeros == 0 {
break
}
len -= zeros
}
return len
}
@[direct_array_access; inline]
fn left_shift_128(a [16]u8, shift int) [16]u8 {
mut res := [16]u8{}
shift_mod := shift % 8
mask := u8((1 << shift_mod) - 1)
offset := shift / 8
for i := 0; i < 16; i++ {
src_idx := i + offset
if src_idx >= 16 {
res[i] = 0
} else {
mut dst := u8(a[i] << shift_mod)
if src_idx + 1 < 16 {
dst |= a[src_idx + 1] >> ((8 - shift_mod) & mask)
}
res[i] = dst
}
}
return res
}
@[direct_array_access; inline]
fn right_shift_128(a [16]u8, shift int) [16]u8 {
mut res := [16]u8{}
shift_mod := shift % 8
mask := u8(0xff) << (8 - shift_mod)
offset := shift / 8
for i := 15; i >= 0; i-- {
src_idx := i - offset
if src_idx < 0 {
res[i] = 0
} else {
mut dst := (u8(0xff) & a[i]) >> shift_mod
if src_idx - 1 >= 0 {
dst |= a[src_idx - 1] << ((8 - shift_mod) & mask)
}
res[i] = dst
}
}
return res
}
@[direct_array_access; inline]
fn bitwise_and_128(a [16]u8, b [16]u8) [16]u8 {
mut res := [16]u8{}
for i := 0; i < 16; i++ {
res[i] = a[i] & b[i]
}
return res
}
@[direct_array_access; inline]
fn bitwise_or_128(a [16]u8, b [16]u8) [16]u8 {
mut res := [16]u8{}
for i := 0; i < 16; i++ {
res[i] = a[i] | b[i]
}
return res
}
@[direct_array_access; inline]
fn bitwise_xor_128(a [16]u8, b [16]u8) [16]u8 {
mut res := [16]u8{}
for i := 0; i < 16; i++ {
res[i] = a[i] ^ b[i]
}
return res
}
// compare_128 returns:
//
// * -1 if a < b
// * 0 if a == b
// * +1 if a > b
@[direct_array_access; inline]
fn compare_128(a [16]u8, b [16]u8) int {
for i in 0 .. 16 {
if a[i] != b[i] {
return if a[i] < b[i] { -1 } else { 1 }
}
}
return 0
}

283
src/eui48.v Normal file
View File

@ -0,0 +1,283 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
module netaddr
import encoding.binary
import math.bits
import rand
import rand.wyrand
pub struct Eui48 {
addr [6]u8
}
// Eui48.new creates new EUI-48 from six octets.
pub fn Eui48.new(a u8, b u8, c u8, d u8, e u8, f u8) Eui48 {
return Eui48{
addr: [a, b, c, d, e, f]!
}
}
// Eui48.from_octets creates new EUI-48 from six-element byte array.
pub fn Eui48.from_octets(addr [6]u8) Eui48 {
return Eui48{addr}
}
// Eui48.from_string parses addr string and returns new EUI-48 instance.
// Example:
// ```
// assert Eui48.from_string('a96:7a87:4ae3')!.str() == '0a-96-7a-87-4a-e3'
// ```
pub fn Eui48.from_string(addr string) !Eui48 {
mut bytes := [6]u8{}
match true {
addr.contains_any('-:') {
// canonical and unix formats
mac := addr.split_any('-:')
if mac.len == 6 {
for i := 0; i < 6; i++ {
if !('0x' + mac[i]).is_hex() {
return error('invalid octet in ${addr}')
}
bytes[i] = ('0x' + mac[i]).u8()
}
} else {
return error('6 octets expected in ${addr}')
}
}
addr.contains('.') {
// cisco triple-hextet format
mac := addr.split('.')
if mac.len == 3 {
mut i := 0
for part in mac {
if !('0x' + part).is_hex() {
return error('non-hexadecimal value in ${addr}')
}
pair := ('0x' + part).u8_array()
bytes[i] = pair[0]
bytes[i + 1] = pair[1]
i += 2
}
} else {
return error('3 hextets expected in ${addr}')
}
}
('0x' + addr).is_hex() {
// bare hex digit
mac := ('0x' + addr).u8_array()
len_diff := 6 - mac.len
if len_diff == 0 {
for i := 0; i < 6; i++ {
bytes[i] = mac[i]
}
} else if len_diff > 0 {
mut i := 0
for pos in len_diff .. 6 {
bytes[pos] = mac[i]
i++
}
} else {
return error('6 octets expected in ${addr}')
}
}
else {
return error('invalid EUI-48 in ${addr}')
}
}
return Eui48{bytes}
}
// Eui48.random is guaranteed to return a locally administered unicast EUI-48.
// By default the WyRandRNG is used with default seed. You can set custom OUI
// if you don't want generate random one.
// Example:
// ```v ignore
// >>> netaddr.Eui48.random()
// be-8c-f7-90-b4-60
// >>> netaddr.Eui48.random(oui: [u8(0x02), 0x0, 0x0]!)
// 02-00-00-2d-1d-01
// ```
pub fn Eui48.random(params Eui48RandomParams) Eui48 {
mut eui := [6]u8{}
mut prng := params.prng
if params.seed.len > 0 {
prng.seed(params.seed)
}
if params.oui != none {
eui[0], eui[1], eui[2] = params.oui[0], params.oui[1], params.oui[2]
} else {
eui[0], eui[1], eui[2] = prng.u8(), prng.u8(), prng.u8()
if (eui[0] >> 1) & 1 == 0 {
eui[0] ^= 0x02 // ensure to address is locally administreted
}
if eui[0] & 1 != 0 {
eui[0] &= ~1 // ensure to address is unicast
}
}
eui[3], eui[4], eui[5] = prng.u8(), prng.u8(), prng.u8()
return Eui48{eui}
}
// str returns EUI-48 string representation in canonical format.
pub fn (e Eui48) str() string {
return e.format(.canonical)
}
// format returns the MAC address as a string formatted according to the fmt rule.
pub fn (e Eui48) format(fmt Eui48Format) string {
mut mac := []string{}
match fmt {
.canonical {
for b in e.addr {
mac << b.hex()
}
return mac.join('-')
}
.unix {
for b in e.addr {
mac << b.hex()
}
return mac.join(':')
}
.hextets {
for i := 0; i <= 4; i += 2 {
mac << e.addr[i..i + 2].hex()
}
return mac.join('.')
}
.bare {
return e.addr[..].hex()
}
}
}
// u8_array returns EUI-48 as byte array.
pub fn (e Eui48) u8_array() []u8 {
return e.addr[..]
}
// u8_array_fixed returns EUI-48 as fixed size byte array.
pub fn (e Eui48) u8_array_fixed() [6]u8 {
return e.addr
}
// bit_len returns number of bits required to represent the current EUI-48.
pub fn (e Eui48) bit_len() int {
return bits.len_64(binary.big_endian_u64(e.addr[..]))
}
// oui_bytes returns the 24 bit Organizationally Unique Identifier (OUI) as byte array.
pub fn (e Eui48) oui_bytes() [3]u8 {
return [e.addr[0], e.addr[1], e.addr[2]]!
}
// ei_bytes returns the 24 bit Extended Identifier (EI) as byte array.
pub fn (e Eui48) ei_bytes() [3]u8 {
return [e.addr[3], e.addr[4], e.addr[5]]!
}
// eui64 returns the EUI-64 converted from EUI-48 via extending address with FF-FE bytes.
pub fn (e Eui48) eui64() Eui64 {
return Eui64{
addr: [e.addr[0], e.addr[1], e.addr[2], 0xff, 0xfe, e.addr[3], e.addr[4], e.addr[5]]!
}
}
// modified_eui64 converts the EUI-48 to Modified EUI-64.
// This is the same as `eui64()`, but the U/L-bit (universal/local bit) is inverted.
pub fn (e Eui48) modified_eui64() Eui64 {
return Eui64{
addr: [(e.addr[0] ^ 0x02), e.addr[1], e.addr[2], 0xff, 0xfe, e.addr[3], e.addr[4], e.addr[5]]!
}
}
// ipv6 creates new IPv6 address from EUI-48. EUI-48 will be converted to
// Modified EUI-64 and appended to network prefix. Byte-reversed `prefix` must fit in 64 bit.
pub fn (e Eui48) ipv6(prefix Ipv6Addr) !Ipv6Addr {
pref := prefix.u8_array_fixed()
eui64 := e.modified_eui64().u8_array_fixed()
if pref[8..] == []u8{len: 8} {
return Ipv6Addr.from_octets([
pref[0],
pref[1],
pref[2],
pref[3],
pref[4],
pref[5],
pref[6],
pref[7],
eui64[0],
eui64[1],
eui64[2],
eui64[3],
eui64[4],
eui64[5],
eui64[6],
eui64[7],
]!)!
}
return error('The prefix ${prefix} is too long. ' +
'At least 64 bits must remain for the interface identifier.')
}
// ipv6_link_local returns link-local IPv6 address created from EUI-48.
pub fn (e Eui48) ipv6_link_local() Ipv6Addr {
return e.ipv6(Ipv6Addr.new(0xfe80, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000) or { Ipv6Addr{} }) or { Ipv6Addr{} }
}
// is_universal returns true if address is universally administreted.
pub fn (e Eui48) is_universal() bool {
// U/L bit is 0
return (e.addr[0] >> 1) & 1 == 0
}
// is_local returns true if address is locally administreted.
pub fn (e Eui48) is_local() bool {
return !e.is_universal()
}
// is_multicast returns true if address is multicast.
pub fn (e Eui48) is_multicast() bool {
return !e.is_unicast()
}
// is_unicast returns true if address is unicast.
pub fn (e Eui48) is_unicast() bool {
// I/G bit is 0
return e.addr[0] & 1 == 0
}
// == returns true if a is equals b.
pub fn (a Eui48) == (b Eui48) bool {
return a.addr == b.addr
}
@[params]
pub struct Eui48RandomParams {
pub:
oui ?[3]u8 // the custom OUI which is used instead of the random one.
seed []u32 // seed for PRNG
prng rand.PRNG = wyrand.WyRandRNG{}
}
pub enum Eui48Format {
canonical // e.g. 0a-96-7a-87-4a-e3
unix // e.g. 0a:96:7a:87:4a:e3
hextets // e.g. 0a96.7a87.4ae3
bare // e.g. 0a967a874ae3
}

240
src/eui64.v Normal file
View File

@ -0,0 +1,240 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
module netaddr
import encoding.binary
import math.bits
pub struct Eui64 {
addr [8]u8
}
// Eui64.new creates new EUI-64 from eigth octets.
pub fn Eui64.new(a u8, b u8, c u8, d u8, e u8, f u8, g u8, h u8) Eui64 {
return Eui64{
addr: [a, b, c, d, e, f, g, h]!
}
}
// Eui64.from_octets creates new EUI-64 from eight-element byte array.
pub fn Eui64.from_octets(addr [8]u8) Eui64 {
return Eui64{addr}
}
// Eui64.from_string parses addr string and returns new EUI-64 instance.
pub fn Eui64.from_string(addr string) !Eui64 {
mut bytes := [8]u8{}
match true {
addr.contains_any('-:') {
// canonical and colon-separated forms
mac := addr.split_any('-:')
if mac.len == 8 {
for i := 0; i < 8; i++ {
if !('0x' + mac[i]).is_hex() {
return error('invalid octet in ${addr}')
}
bytes[i] = ('0x' + mac[i]).u8()
}
} else {
return error('8 octets expected in ${addr}')
}
}
addr.contains('.') {
// period separated hextets
mac := addr.split('.')
if mac.len == 4 {
mut i := 0
for part in mac {
if !('0x' + part).is_hex() {
return error('non-hexadecimal value in ${addr}')
}
pair := ('0x' + part).u8_array()
bytes[i] = pair[0]
bytes[i + 1] = pair[1]
i += 2
}
} else {
return error('four hextets expected in ${addr}')
}
}
('0x' + addr).is_hex() {
// bare hex digit
mac := ('0x' + addr).u8_array()
len_diff := 8 - mac.len
if len_diff == 0 {
for i := 0; i < 8; i++ {
bytes[i] = mac[i]
}
} else if len_diff > 0 {
mut i := 0
for pos in len_diff .. 6 {
bytes[pos] = mac[i]
i++
}
} else {
return error('8 octets expected in ${addr}')
}
}
else {
return error('invalid EUI-64 in ${addr}')
}
}
return Eui64{bytes}
}
// str returns EUI-64 string representation in canonical format.
pub fn (e Eui64) str() string {
return e.format(.canonical)
}
// format returns the EUI-64 as a string formatted according to the fmt rule.
pub fn (e Eui64) format(fmt Eui64Format) string {
mut mac := []string{}
match fmt {
.canonical {
for b in e.addr {
mac << b.hex()
}
return mac.join('-')
}
.unix {
for b in e.addr {
mac << b.hex()
}
return mac.join(':')
}
.hextets {
for i := 0; i <= 6; i += 2 {
mac << e.addr[i..i + 2].hex()
}
return mac.join('.')
}
.bare {
return e.addr[..].hex()
}
}
}
// u8_array returns EUI-64 as byte array.
pub fn (e Eui64) u8_array() []u8 {
return e.addr[..]
}
// u8_array_fixed returns EUI-64 as fixed size byte array.
pub fn (e Eui64) u8_array_fixed() [8]u8 {
return e.addr
}
// bit_len returns number of bits required to represent the current EUI-64.
pub fn (e Eui64) bit_len() int {
return bits.len_64(binary.big_endian_u64(e.addr[..]))
}
// oui_bytes returns the 24 bit Organizationally Unique Identifier (OUI) as byte array.
pub fn (e Eui64) oui_bytes() [3]u8 {
return [e.addr[0], e.addr[1], e.addr[2]]!
}
// ei_bytes returns the 40 bit Extended Identifier (EI) as byte array.
pub fn (e Eui64) ei_bytes() [5]u8 {
return [e.addr[3], e.addr[4], e.addr[5], e.addr[6], e.addr[7]]!
}
// modified_eui64 returns the Modified EUI-64 Format Interface Identifier per RFC 4291 (Appendix A).
pub fn (e Eui64) modified_eui64() Eui64 {
mut addr := [8]u8{}
for i in 0 .. 8 {
addr[i] = e.addr[i]
}
addr[0] ^= 0x02
return Eui64{addr}
}
// ipv6 creates new IPv6 address from Modified EUI-64.
// Byte-reversed `prefix` must fit in 64 bit.
// Example:
// ```
// pref := netaddr.Ipv6Net.from_string('2001:0db8:ef01:2345::/64')!
// eui := netaddr.Eui64.from_string('aa-bb-cc-dd-ee-ff-00-11')!
// ip6 := eui.ipv6(pref.network_address)!
// println(ip6) // 2001:0db8:ef01:2345:a8bb:ccdd:eeff:11
// ```
pub fn (e Eui64) ipv6(prefix Ipv6Addr) !Ipv6Addr {
pref := prefix.u8_array_fixed()
eui64 := e.modified_eui64().u8_array_fixed()
if pref[8..] == []u8{len: 8} {
return Ipv6Addr.from_octets([
pref[0],
pref[1],
pref[2],
pref[3],
pref[4],
pref[5],
pref[6],
pref[7],
eui64[0],
eui64[1],
eui64[2],
eui64[3],
eui64[4],
eui64[5],
eui64[6],
eui64[7],
]!)!
}
return error('The prefix ${prefix} is too long. ' +
'At least 64 bits must remain for the interface identifier.')
}
// ipv6_link_local returns link-local IPv6 address created from Modified EUI-64.
pub fn (e Eui64) ipv6_link_local() Ipv6Addr {
return e.ipv6(Ipv6Addr.new(0xfe80, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000) or { Ipv6Addr{} }) or { Ipv6Addr{} }
}
// is_universal returns true if address is universally administreted.
pub fn (e Eui64) is_universal() bool {
// U/L bit is 0
return (e.addr[0] >> 1) & 1 == 0
}
// is_local returns true if address is locally administreted.
pub fn (e Eui64) is_local() bool {
return !e.is_universal()
}
// is_multicast returns true if address is multicast.
pub fn (e Eui64) is_multicast() bool {
return !e.is_unicast()
}
// is_unicast returns true if address is unicast.
pub fn (e Eui64) is_unicast() bool {
// I/G bit is 0
return e.addr[0] & 1 == 0
}
// == returns true if a is equals b.
pub fn (a Eui64) == (b Eui64) bool {
return a.addr == b.addr
}
pub enum Eui64Format {
canonical // e.g. 0a-96-7a-ff-fe-87-4a-e3
unix // e.g. 0a:96:7a:ff:fe:87:4a:e3
hextets // e.g. 0a96.7aff.ffe87.4ae3
bare // e.g. 0a967afffe874ae3
}

547
src/ip.v Normal file
View File

@ -0,0 +1,547 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
module netaddr
import encoding.binary
import math.bits
import net
pub struct Ipv4Addr {
addr [4]u8
}
// Ipv4Addr.new creates new Ipv4Addr instance from four octets.
pub fn Ipv4Addr.new(a u8, b u8, c u8, d u8) Ipv4Addr {
return Ipv4Addr{
addr: [a, b, c, d]!
}
}
// Ipv4Addr.from_octets creates new Ipv4Addr instance from four-element byte array.
pub fn Ipv4Addr.from_octets(addr [4]u8) Ipv4Addr {
return Ipv4Addr{addr}
}
// Ipv4Addr.from_string parses addr string and creates new Ipv4Addr instance.
// Only dotted-decimal form is allowed e.g. 203.0.113.5.
pub fn Ipv4Addr.from_string(addr string) !Ipv4Addr {
octets := addr.split('.')
if octets.len != 4 {
return error('expected 4 octets in ${addr}')
}
mut bytes := [4]u8{}
for i := 0; i < 4; i++ {
bytes[i] = u8(octets[i].parse_uint(10, 8) or {
return error('${octets[i]} is not valid unsigned 8 bit integer in ${addr}')
})
}
return Ipv4Addr{bytes}
}
// Ipv4Addr.from_u32 creates new Ipv4Addr instance from unsigned 32 bit integer.
pub fn Ipv4Addr.from_u32(addr u32) Ipv4Addr {
mut bytes := [4]u8{}
binary.big_endian_put_u32_fixed(mut bytes, addr)
return Ipv4Addr{bytes}
}
// str returns string representation of IP address.
pub fn (a Ipv4Addr) str() string {
// string concatenation is much faster than interpolation
return a.addr[0].str() + '.' + a.addr[1].str() + '.' + a.addr[2].str() + '.' + a.addr[3].str()
}
// u32 returns IP address represented as unsigned 32 bit integer.
pub fn (a Ipv4Addr) u32() u32 {
return binary.big_endian_u32_fixed(a.addr)
}
// u8_array returns IP address represented as byte array.
pub fn (a Ipv4Addr) u8_array() []u8 {
return a.addr[..]
}
// u8_array_fixed returns IP address represented as fixed size byte array.
pub fn (a Ipv4Addr) u8_array_fixed() [4]u8 {
return a.addr
}
// ipv6 returns IPv4-mapped or IPv4-compatible IPv6 address per RFC 4291.
// By default returns the IPv4-mapped IPv6 address e.g. ::ffff:203.0.113.90.
pub fn (a Ipv4Addr) ipv6(params Ipv4ToIpv6Params) Ipv6Addr {
mut bytes := [16]u8{}
if params.kind == .mapped {
bytes[10] = u8(255)
bytes[11] = u8(255)
}
bytes[12] = a.addr[0]
bytes[13] = a.addr[1]
bytes[14] = a.addr[2]
bytes[15] = a.addr[3]
return Ipv6Addr{
addr: bytes
}
}
// bit_len returns number of bits required to represent IP address.
// Example:
// ```
// assert netaddr.Ipv4Addr.new(0, 0, 255, 255).bit_len() == 16
// ```
pub fn (a Ipv4Addr) bit_len() int {
return bits.len_32(a.u32())
}
// family returns the `net.AddrFamily` member corresponding to IP version.
pub fn (a Ipv4Addr) family() net.AddrFamily {
return .ip // net.AddrFamily.ip means IP version 4
}
// reverse_pointer returns reverse DNS record for the IP address in .in-addr.arpa zone.
pub fn (a Ipv4Addr) reverse_pointer() string {
return a.str().split('.').reverse().join('.') + '.in-addr.arpa'
}
// is_link_local returns true if the address is reserved for link-local usage.
pub fn (a Ipv4Addr) is_link_local() bool {
return ipv4_link_local_network.contains(a)
}
// is_loopback returns true if this is a loopback address.
pub fn (a Ipv4Addr) is_loopback() bool {
return ipv4_loopback_network.contains(a)
}
// is_multicast returns true if the address is reserved for multicast use.
pub fn (a Ipv4Addr) is_multicast() bool {
return ipv4_multicast_network.contains(a)
}
// is_unicast returns true if the address is unicast.
pub fn (a Ipv4Addr) is_unicast() bool {
return !a.is_multicast()
}
// is_shared returns true if the address is allocated in shared address space.
// See RFC 6598. Addresses from network 100.64.0.0/10 is both not "private" and
// not "global", so is_private and is_global methods returns false for it.
pub fn (a Ipv4Addr) is_shared() bool {
return ipv4_public_network.contains(a)
}
// is_private returns true if the address is not globally reachable.
pub fn (a Ipv4Addr) is_private() bool {
return ipv4_private_networks.any(it.contains(a) == true)
&& ipv4_private_networks_exceptions.all(it.contains(a) == false)
}
// is_global return true if the address is globally reachable.
pub fn (a Ipv4Addr) is_global() bool {
return !a.is_private() && !ipv4_public_network.contains(a)
}
// is_reserved returns true if the address is IETF reserved.
pub fn (a Ipv4Addr) is_reserved() bool {
return ipv4_reserved_network.contains(a)
}
// is_unspecified returns true if the address is unspecified i.e. equals 0.0.0.0.
pub fn (a Ipv4Addr) is_unspecified() bool {
return a.addr == [4]u8{}
}
// is_netmask returns true if IP address is network mask.
pub fn (a Ipv4Addr) is_netmask() bool {
intval := (a.u32() ^ max_u32) + 1
return intval & (intval - 1) == 0
}
// is_hostmask returns true if IP address is host mask.
pub fn (a Ipv4Addr) is_hostmask() bool {
return (a.u32() + 1) & a.u32() == 0
}
// < returns true if a is lesser than b.
pub fn (a Ipv4Addr) < (b Ipv4Addr) bool {
return a.u32() < b.u32()
}
// == returns true if a equals b.
pub fn (a Ipv4Addr) == (b Ipv4Addr) bool {
return a.addr == b.addr
}
@[params]
pub struct Ipv4ToIpv6Params {
pub:
kind Ipv6WithEmbeddedIpv4 = .mapped
}
// See RFC 4291 Section 2.5.5.
pub enum Ipv6WithEmbeddedIpv4 {
mapped // e.g. ::ffff:203.0.113.90
compat // e.g. ::203.0.113.90, deprecated per RFC 4291 Section 4
}
pub struct Ipv4Net {
pub:
network_address Ipv4Addr
network_mask Ipv4Addr
host_mask Ipv4Addr
broadcast_address Ipv4Addr
host_address ?Ipv4Addr
prefix_len int
mut:
current u32
}
// Ipv4Net.new creates new Ipv4Net from network *addr* with given *prefix* length.
pub fn Ipv4Net.new(addr Ipv4Addr, prefix int) !Ipv4Net {
if prefix < 0 || prefix > 32 {
return error('prefix length must be in range 0-32, not ${prefix}')
}
net_mask := max_u32 ^ (max_u32 >> prefix)
mut net_addr := addr
mut host_addr := ?Ipv4Addr(none)
if (net_addr.u32() & net_mask) != net_addr.u32() {
host_addr = Ipv4Addr{net_addr.u8_array_fixed()}
net_addr = Ipv4Addr.from_u32(net_addr.u32() & net_mask)
}
host_mask := net_mask ^ max_u32
broadcast := net_addr.u32() | host_mask
return Ipv4Net{
network_address: net_addr
network_mask: Ipv4Addr.from_u32(net_mask)
host_mask: Ipv4Addr.from_u32(host_mask)
broadcast_address: Ipv4Addr.from_u32(broadcast)
host_address: host_addr
prefix_len: prefix
current: net_addr.u32()
}
}
// Ipv4Net.from_string parses cidr and creates new Ipv4Net.
// Allowed formats are:
//
// * single IP address without prefix length, 32 is applied;
// * network address with non-negative integer prefix length e.g. 172.16.16.0/24;
// * network address with host mask: 172.16.16.0/0.0.0.255;
// * network address with network mask: 172.16.16.0/255.255.255.0.
//
// If prefix length is greather than 32 and host bits is set in the network address
// the optional `host_address` field will be filled with this host address.
// The `network_address` field always will contain the real network address.
pub fn Ipv4Net.from_string(cidr string) !Ipv4Net {
if cidr.is_blank() {
return error('network address cannot be blank')
}
mut net_addr_str, mut prefix_str := '', ''
cidr_parts := cidr.split_nth('/', 2)
if cidr_parts.len == 1 {
net_addr_str, prefix_str = cidr_parts[0], '32'
} else {
net_addr_str, prefix_str = cidr_parts[0], cidr_parts[1]
}
mut net_addr := Ipv4Addr.from_string(net_addr_str) or {
return error('invalid IPv4 address in ${cidr}')
}
mut prefix_len := 0
mut host_mask := Ipv4Addr{}
mut net_mask := Ipv4Addr.from_u32(max_u32)
mut host_addr := ?Ipv4Addr(none)
if prefix_u64 := prefix_str.parse_uint(10, 32) {
prefix_len = int(prefix_u64)
if prefix_len < 32 {
net_mask = Ipv4Addr.from_u32(max_u32 ^ (max_u32 >> u32(prefix_len)))
}
host_mask = Ipv4Addr.from_u32(net_mask.u32() ^ max_u32)
} else {
mut mask := Ipv4Addr.from_string(prefix_str) or {
return error('invalid prefix length in ${cidr}')
}
if mask.is_netmask() || mask.addr == [4]u8{} || mask.addr == [4]u8{init: 255} {
net_mask = mask
host_mask = Ipv4Addr.from_u32(mask.u32() ^ max_u32)
prefix_len = 32 - host_mask.bit_len()
} else if mask.is_hostmask() {
host_mask = mask
prefix_len = 32 - mask.bit_len()
if prefix_len < 32 {
net_mask = Ipv4Addr.from_u32(max_u32 ^ (max_u32 >> u32(prefix_len)))
}
} else {
return error('${mask} is not valid host or network mask in ${cidr}')
}
}
if (net_addr.u32() & net_mask.u32()) != net_addr.u32() {
host_addr = Ipv4Addr{net_addr.u8_array_fixed()}
net_addr = Ipv4Addr.from_u32(net_addr.u32() & net_mask.u32())
}
broadcast := Ipv4Addr.from_u32(net_addr.u32() | host_mask.u32())
return Ipv4Net{
network_address: net_addr
network_mask: net_mask
host_mask: host_mask
broadcast_address: broadcast
host_address: host_addr
prefix_len: prefix_len
current: net_addr.u32()
}
}
// Ipv4Net.from_u32 creates new Ipv4Net from network *addr* with given *prefix* length.
pub fn Ipv4Net.from_u32(addr u32, prefix int) !Ipv4Net {
if prefix < 0 || prefix > 32 {
return error('prefix length must be in range 0-32, not ${prefix}')
}
mut host_addr := ?Ipv4Addr(none)
mut net_addr := addr
net_mask := max_u32 ^ (max_u32 >> prefix)
if (net_addr & net_mask) != net_addr {
mut net_addr_bytes := [4]u8{}
binary.big_endian_put_u32_fixed(mut net_addr_bytes, net_addr)
host_addr = Ipv4Addr{net_addr_bytes}
net_addr &= net_mask
}
host_mask := net_mask ^ max_u32
broadcast := net_addr | host_mask
return Ipv4Net{
network_address: Ipv4Addr.from_u32(net_addr)
network_mask: Ipv4Addr.from_u32(net_mask)
host_mask: Ipv4Addr.from_u32(host_mask)
broadcast_address: Ipv4Addr.from_u32(broadcast)
host_address: host_addr
prefix_len: prefix
current: net_addr
}
}
// str returns string representation of IPv4 network in CIDR format.
pub fn (n Ipv4Net) str() string {
return n.format(.with_prefix_len)
}
// format returns the IPv4 network as a string formatted according to the fmt rule.
pub fn (n Ipv4Net) format(fmt Ipv4NetFormat) string {
match fmt {
.with_prefix_len {
return n.network_address.str() + '/' + n.prefix_len.str()
}
.with_host_mask {
return n.network_address.str() + '/' + n.host_mask.str()
}
.with_network_mask {
return n.network_address.str() + '/' + n.network_mask.str()
}
}
}
// capacity returns a total number of addresses in the network.
pub fn (n Ipv4Net) capacity() u64 {
return u64(n.broadcast_address.u32() - n.network_address.u32()) + 1
}
// next implements an iterator that iterates over all addresses in network
// including network and broadcast addresses.
// Example:
// ```
// network := netaddr.Ipv4Net.from_string('10.0.10.2/29')!
// for addr in network {
// println(addr)
// }
// ```
pub fn (mut n Ipv4Net) next() ?Ipv4Addr {
if n.current >= n.broadcast_address.u32() + 1 {
return none
}
defer {
n.current++
}
return Ipv4Addr.from_u32(n.current)
}
// first returns the first usable host address in network.
pub fn (n Ipv4Net) first() Ipv4Addr {
if n.prefix_len in [31, 32] {
return n.network_address
}
return Ipv4Addr.from_u32(n.network_address.u32() + 1)
}
// last returns the last usable host address in network.
pub fn (n Ipv4Net) last() Ipv4Addr {
if n.prefix_len in [31, 32] {
return n.broadcast_address
}
return Ipv4Addr.from_u32(n.broadcast_address.u32() - 1)
}
// nth returns the Nth address in network. Supports negative indexes.
pub fn (n Ipv4Net) nth(num i64) !Ipv4Addr {
mut addr := Ipv4Addr{}
if num >= 0 {
addr = Ipv4Addr.from_u32(n.network_address.u32() + u32(num))
} else {
addr = Ipv4Addr.from_u32(n.broadcast_address.u32() + u32(num + 1))
}
if n.contains(addr) {
return addr
}
return error('unable to get ${num}th address')
}
// contains returns true if IP address is in the network.
pub fn (n Ipv4Net) contains(addr Ipv4Addr) bool {
return n.network_address.u32() <= addr.u32() && addr.u32() <= n.broadcast_address.u32()
}
// overlaps returns true if network partly contains in *other*,
// in other words if the networks addresses sets intersect.
pub fn (n Ipv4Net) overlaps(other Ipv4Net) bool {
return other.contains(n.network_address) || (other.contains(n.broadcast_address)
|| (n.contains(other.network_address) || (n.contains(other.broadcast_address))))
}
// subnets returns iterator that iterates over the network subnets partitioned by given *prefix* length.
// Example:
// ```
// network := netaddr.Ipv4Net.from_string('198.51.100.0/24')!
// subnets := network.subnets(26)!
// for subnet in subnets {
// println(subnet)
// }
// ```
pub fn (n Ipv4Net) subnets(prefix int) !Ipv4NetsIterator {
if prefix > 32 || prefix < n.prefix_len {
return error('prefix length must be in range ${n.prefix_len}-32, not ${prefix}')
}
return Ipv4NetsIterator{
prefix_len: prefix
step: (n.host_mask.u32() + 1) >> (prefix - n.prefix_len)
end: n.broadcast_address.u32()
current: n.network_address.u32()
}
}
// supernet returns IPv4 network containing the current network.
pub fn (n Ipv4Net) supernet(prefix int) !Ipv4Net {
if prefix < 0 || prefix > n.prefix_len {
return error('prefix length must be in range 0-${n.prefix_len}, not ${prefix}')
}
if prefix == 0 {
return n
}
net_addr := n.network_address.u32() & (n.network_mask.u32() << (n.prefix_len - prefix))
return Ipv4Net.from_u32(net_addr, prefix)!
}
// is_subnet_of returns true if *other* contains the network.
pub fn (n Ipv4Net) is_subnet_of(other Ipv4Net) bool {
return other.network_address.u32() <= n.network_address.u32()
&& other.broadcast_address.u32() >= n.broadcast_address.u32()
}
// is_supernet_of returns true if the network contains *other*.
pub fn (n Ipv4Net) is_supernet_of(other Ipv4Net) bool {
return n.network_address.u32() <= other.network_address.u32()
&& n.broadcast_address.u32() >= other.broadcast_address.u32()
}
// is_link_local returns true if the network is link-local.
pub fn (n Ipv4Net) is_link_local() bool {
return n.network_address.is_link_local() && n.broadcast_address.is_link_local()
}
// is_loopback returns true if this is a loopback network.
pub fn (n Ipv4Net) is_loopback() bool {
return n.network_address.is_loopback() && n.broadcast_address.is_loopback()
}
// is_multicast returns true if the network is reserved for multicast use.
pub fn (n Ipv4Net) is_multicast() bool {
return n.network_address.is_multicast() && n.broadcast_address.is_multicast()
}
// is_unicast returns true if the network is unicast.
pub fn (n Ipv4Net) is_unicast() bool {
return !n.is_multicast()
}
// is_shared returns true if the network is in shared address space.
pub fn (n Ipv4Net) is_shared() bool {
return n.network_address.is_shared() && n.broadcast_address.is_shared()
}
// is_private returns true if the network is not globally reachable.
pub fn (n Ipv4Net) is_private() bool {
return n.network_address.is_private() && n.broadcast_address.is_private()
}
// is_global return true if the network is globally reachable.
pub fn (n Ipv4Net) is_global() bool {
return !n.is_private()
}
// is_reserved returns true if the network is IETF reserved.
pub fn (n Ipv4Net) is_reserved() bool {
return n.network_address.is_reserved() && n.broadcast_address.is_reserved()
}
// is_unspecified returns true if the network is 0.0.0.0/32.
pub fn (n Ipv4Net) is_unspecified() bool {
return n.network_address.is_unspecified() && n.broadcast_address.is_unspecified()
}
// < returns true if the network is lesser than other network.
pub fn (n Ipv4Net) < (other Ipv4Net) bool {
if n.network_address != other.network_address {
return n.network_address.u32() < other.network_address.u32()
}
if n.network_mask != other.network_mask {
return n.network_mask.u32() < other.network_mask.u32()
}
return false
}
// == returns true if networks equals.
pub fn (n Ipv4Net) == (other Ipv4Net) bool {
return n.network_address == other.network_address && n.network_mask == n.network_mask
}
pub enum Ipv4NetFormat {
with_prefix_len // e.g. 198.51.100.0/24
with_host_mask // e.g. 198.51.100.0/0.0.0.255
with_network_mask // e.g. 198.51.100.0/255.255.255.0
}
pub struct Ipv4NetsIterator {
prefix_len int
step u32
end u32
mut:
current u32
}
// next implements the iterator interface for IP network subnets.
pub fn (mut iter Ipv4NetsIterator) next() ?Ipv4Net {
if iter.current >= iter.end + 1 {
return none
}
defer {
iter.current += iter.step
}
return Ipv4Net.from_u32(iter.current, iter.prefix_len)!
}

884
src/ip6.v Normal file
View File

@ -0,0 +1,884 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
module netaddr
import encoding.binary
import math.big
import net
const max_u128 = big.integer_from_bytes([]u8{len: 16, init: 0xff})
pub struct Ipv6Addr {
addr [16]u8
pub:
zone_id ?string // the IPv6 scope zone identifier per RFC 4007
}
// Ipv6Addr.new creates new Ipv6Addr instance from eight 16-bit segments with optional
// scope zone_id.
// Example:
// ```
// import netaddr
//
// ip := netaddr.Ipv6Addr.new(0x2001, 0x0db8, 0x0008, 0x0004, 0x0000, 0x0000, 0x0000, 0x0002)!
// println(ip) // 2001:db8:8:4::2
// ```
pub fn Ipv6Addr.new(a u16, b u16, c u16, d u16, e u16, f u16, g u16, h u16, params Ipv6AddrParams) !Ipv6Addr {
params.validate()!
mut addr := [16]u8{}
mut one := [2]u8{}
mut nr := 0
for segment in [a, b, c, d, e, f, g, h] {
binary.big_endian_put_u16_fixed(mut one, segment)
addr[nr] = one[0]
addr[nr + 1] = one[1]
nr += 2
}
return Ipv6Addr{
addr: addr
zone_id: params.zone_id
}
}
// Ipv6Addr.from_segments creates new Ipv6Addr instance from eight 16-bit segments
// with optional scope zone_id.
pub fn Ipv6Addr.from_segments(seg [8]u16, params Ipv6AddrParams) !Ipv6Addr {
return Ipv6Addr.new(seg[0], seg[1], seg[2], seg[3], seg[4], seg[5], seg[6], seg[7],
params)!
}
// Ipv6Addr.from_octets creates new Ipv6Addr instance from 16 octets
// with optional scope zone_id.
pub fn Ipv6Addr.from_octets(addr [16]u8, params Ipv6AddrParams) !Ipv6Addr {
params.validate()!
return Ipv6Addr{
addr: addr
zone_id: params.zone_id
}
}
// Ipv6Addr.from_string parses addr and returns new Ipv6Addr instance.
// The allowed formats are:
//
// * full length hexadecimal colon-separated address e.g. aaaa:bbbb:cccc:dddd:eeee:ffff:0000:1111;
// * address with omitted leading zeros in hextets;
// * address with omitted all-zeros hextets e.g. ::1;
// * combined form with omitted all-zeros and leading zeros;
// * mixed with dotted-decimal format e.g. ::ffff:192.168.3.12;
// * address with scope zone identifier e.g. fe80::d08e:6658%eth0;
// * address in square brackets: [a:b:c:d:e:f:0:1].
pub fn Ipv6Addr.from_string(addr string) !Ipv6Addr {
if addr.is_blank() {
return error('IP address cannot be blank')
}
if addr.contains('/') {
return error("unexpected '/' in ${addr}")
}
addr_clean, zone_id := split_scope(addr.trim('[]')) or { return err }
if addr_clean.count('::') > 1 {
return error('too many :: in ${addr}')
}
if addr_clean[0] == u8(`:`) && !addr_clean.starts_with('::') {
return error('leading : is allowed only as :: part in ${addr}')
}
if addr_clean[addr_clean.len - 1] == u8(`:`) && !addr_clean.ends_with('::') {
return error('trailing : is allowed only as :: part in ${addr}')
}
mut hextets := addr_clean.split(':')
if hextets.len < 3 {
return error('at least 3 parts expected in ${addr}')
}
for i, hextet in hextets {
if hextet.contains('.') && i == hextets.len - 1 {
ip4 := Ipv4Addr.from_string(hextet) or {
return error('invalid IPv6-embedded IPv4 address in ${addr}')
}
ip4_u8 := ip4.u8_array_fixed()
hextets.delete(i)
hextets << ip4_u8[0].hex() + ip4_u8[1].hex()
hextets << ip4_u8[2].hex() + ip4_u8[3].hex()
}
}
len_diff := 8 - hextets.len
if len_diff < 8 && len_diff > 0 {
for i := 0; i < len_diff + 1; i++ {
// insert missing hextets with zero values
hextets.insert(hextets.index(''), '0')
}
hextets.delete(hextets.index('')) // delete extra empty item
} else if len_diff < 0 {
// too many hextets (more than 8) in address
return error('unable to parse IPv6 address from string ${addr}')
}
// replace empty strings with zeros
for i := 0; i < hextets.len; i++ {
if hextets[i] == '' {
hextets[i] = '0'
}
}
mut address := [16]u8{}
mut i := 0
for hextet in hextets {
in_hex := '0x' + hextet
if !in_hex.is_hex() {
return error('non-hexadecimal value ${hextet} in ${addr}')
}
mut pair := in_hex.u8_array()
if pair.len == 1 {
// add leading zero to fit into len=2
pair << u8(0)
pair[0], pair[1] = pair[1], pair[0]
}
address[i] = pair[0]
address[i + 1] = pair[1]
i += 2
}
return Ipv6Addr{address, zone_id}
}
// Ipv6Addr.from_bigint creates new Ipv6Addr from big.Integer with optional scope
// zone_id. The integer sign will be discarded. `addr` must fit in 128 bit.
pub fn Ipv6Addr.from_bigint(addr big.Integer, params Ipv6AddrParams) !Ipv6Addr {
params.validate()!
if addr.bit_len() > 128 {
return error('${addr} overflows 128 bit')
}
mut address := [16]u8{}
bytes, _ := addr.bytes()
len_diff := 16 - bytes.len
if len_diff == 0 {
for i in 0 .. 16 {
address[i] = bytes[i]
}
} else {
mut i := 0
for pos in len_diff .. 16 {
address[pos] = bytes[i]
i++
}
}
return Ipv6Addr{
addr: address
zone_id: params.zone_id
}
}
// str returns string representation of IPv6 address in compact format.
pub fn (a Ipv6Addr) str() string {
return a.format(.compact | .dotted)
}
// format returns the IPv6 address as a string formatted according to the fmt rule.
pub fn (a Ipv6Addr) format(fmt Ipv6AddrFormat) string {
mut str := []string{}
match true {
fmt & .compact == .compact {
if fmt & .dotted == .dotted {
if a.is_ipv4_mapped() {
return '::ffff:' +
Ipv4Addr{[a.addr[12], a.addr[13], a.addr[14], a.addr[15]]!}.str()
}
if a.is_ipv4_compat() {
return '::' + Ipv4Addr{[a.addr[12], a.addr[13], a.addr[14], a.addr[15]]!}.str()
}
}
for i := 0; i <= 14; i += 2 {
mut hextet := a.addr[i..i + 2].hex().trim_left('0')
if hextet == '' {
hextet = '0'
}
str << hextet
}
// Find largest sequence of zeros and replace it with empty string
mut zeros_seq_begin := -1
mut zeros_seq_len := 0
mut max_zeros_seq_begin := -1
mut max_zeros_seq_len := 0
for i, hx in str {
if hx == '0' {
zeros_seq_len++
if zeros_seq_begin == -1 {
zeros_seq_begin = i
}
if zeros_seq_len > max_zeros_seq_len {
max_zeros_seq_len = zeros_seq_len
max_zeros_seq_begin = zeros_seq_begin
}
} else {
zeros_seq_len = 0
zeros_seq_begin = -1
}
}
if max_zeros_seq_len > 1 {
if str.len == max_zeros_seq_begin + max_zeros_seq_len {
str << ''
}
str.delete_many(max_zeros_seq_begin, max_zeros_seq_len)
if max_zeros_seq_begin == 0 {
str.insert(0, '')
}
str.insert(max_zeros_seq_begin, '')
}
if a.zone_id == none {
return str.join(':')
}
return str.join(':') + '%' + (a.zone_id as string)
}
fmt & .verbose == .verbose {
if fmt & .dotted == .dotted {
if a.is_ipv4_mapped() {
return '0000:0000:0000:0000:0000:ffff:' +
Ipv4Addr{[a.addr[12], a.addr[13], a.addr[14], a.addr[15]]!}.str()
}
if a.is_ipv4_compat() {
return '0000:0000:0000:0000:0000:0000:' +
Ipv4Addr{[a.addr[12], a.addr[13], a.addr[14], a.addr[15]]!}.str()
}
}
for i := 0; i <= 14; i += 2 {
str << a.addr[i..i + 2].hex()
}
if a.zone_id == none {
return str.join(':')
}
return str.join(':') + '%' + (a.zone_id as string)
}
else {
return a.str()
}
}
}
// bigint returns IP address represented as big.Integer.
pub fn (a Ipv6Addr) bigint() big.Integer {
if a.addr == [16]u8{} {
return big.zero_int
}
return big.integer_from_bytes(a.addr[..])
}
// u8_array returns IP address represented as byte array.
pub fn (a Ipv6Addr) u8_array() []u8 {
return a.addr[..]
}
// u8_array_fixed returns IP address represented as fixed size byte array.
pub fn (a Ipv6Addr) u8_array_fixed() [16]u8 {
return a.addr
}
// segments returns an array of eight 16-bit IP address segments.
pub fn (a Ipv6Addr) segments() [8]u16 {
mut segments := [8]u16{}
mut nr := 0
for i in 0 .. 8 {
segments[i] = binary.big_endian_u16_fixed([a.addr[nr], a.addr[nr + 1]]!)
nr += 2
}
return segments
}
// with_scope returns IPv6 address with new zone_id.
// Note: with_scope creates new Ipv6Addr, does not change the current.
pub fn (a Ipv6Addr) with_scope(zone_id string) !Ipv6Addr {
if zone_id.is_blank() || zone_id.contains('%') {
return error('zone_id cannot be blank or contain % sign')
}
return Ipv6Addr{a.addr, zone_id}
}
// ipv4 returns IPv4 address converted from IPv4-mapped or IPv4-compatible IPv6 address.
// Note: this function does not treat :: and ::1 addresses as IPv4-compatible ones.
pub fn (a Ipv6Addr) ipv4() !Ipv4Addr {
if a.is_ipv4_mapped() || a.is_ipv4_compat() {
return Ipv4Addr{[a.addr[12], a.addr[13], a.addr[14], a.addr[15]]!}
}
return error('${a} is not IPv4-mapped or IPv4-compatible address')
}
// six_to_four returns embedded IPv4 address if the IPv6 address is 6to4. See RFC 3056.
pub fn (a Ipv6Addr) six_to_four() !Ipv4Addr {
if a.addr[..2] != [u8(0x20), 2] {
return error('${a} is not a 6to4 address')
}
return Ipv4Addr{[a.addr[2], a.addr[3], a.addr[4], a.addr[5]]!}
}
// teredo returns embedded Teredo address.
// See RFC 4380 and https://en.wikipedia.org/wiki/Teredo_tunneling
pub fn (a Ipv6Addr) teredo() !TeredoAddr {
if a.addr[..4] != [u8(0x20), 1, 0, 0] {
return error('${a} is not a Teredo address')
}
return TeredoAddr{
server: Ipv4Addr{[a.addr[4], a.addr[5], a.addr[6], a.addr[7]]!}
flags: binary.big_endian_u16(a.addr[8..10])
port: binary.big_endian_u16([~a.addr[10], ~a.addr[11]])
client: Ipv4Addr{[~a.addr[12], ~a.addr[13], ~a.addr[14], ~a.addr[15]]!}
}
}
// bit_len returns number of bits required to represent IP address.
pub fn (a Ipv6Addr) bit_len() int {
return bit_len_128(a.addr)
}
// family returns the `net.AddrFamily` member corresponding to IP version.
pub fn (a Ipv6Addr) family() net.AddrFamily {
return .ip6
}
// reverse_pointer returns a reverse DNS pointer name for IPv6 address.
pub fn (a Ipv6Addr) reverse_pointer() string {
return a.addr[..].hex().split('').reverse().join('.') + '.ip6.arpa'
}
// is_ipv4_mapped returns true if IPv6 address is IPv4-mapped.
pub fn (a Ipv6Addr) is_ipv4_mapped() bool {
return a.addr[..10].all(it == u8(0)) && a.addr[10] == 255 && a.addr[11] == 255
}
// is_ipv4_compat returns true if IPv6 address is IPv4-compatible.
// Note: loopback and unspecified addresses (::1 and :: respectively) are not
// recognized as IPv4-compatible addresses.
pub fn (a Ipv6Addr) is_ipv4_compat() bool {
return a.addr[..12].all(it == u8(0)) && a.addr[12..16] !in [[u8(0), 0, 0, 0], [u8(0), 0, 0, 1]]
}
// is_site_local returns true if the address is reserved for site local usage.
// See RFC 3879.
pub fn (a Ipv6Addr) is_site_local() bool {
return ipv6_site_local_network.contains(a)
}
// is_unique_local returns true if the address is unique local. See RFC 4193, RFC 8190.
pub fn (a Ipv6Addr) is_unique_local() bool {
return ipv6_unique_local_network.contains(a)
}
// is_link_local returns true if the address is allocated in link-local network.
pub fn (a Ipv6Addr) is_link_local() bool {
ip := a.ipv4() or { return ipv6_link_local_network.contains(a) }
return ip.is_link_local()
}
// is_loopback returns true if the address is loopback i.e equals ::1.
pub fn (a Ipv6Addr) is_loopback() bool {
ip := a.ipv4() or { return a.addr == [u8(0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]! }
return ip.is_loopback()
}
// is_multicast returns true if the address is reserved for multicast use.
pub fn (a Ipv6Addr) is_multicast() bool {
ip := a.ipv4() or { return ipv6_multicast_network.contains(a) }
return ip.is_multicast()
}
// is_unicast returns true if the address is unicast.
pub fn (a Ipv6Addr) is_unicast() bool {
return !a.is_multicast()
}
// is_private returns true if the address is not globally reachable.
pub fn (a Ipv6Addr) is_private() bool {
ip := a.ipv4() or {
return ipv6_private_networks.any(it.contains(a) == true)
&& ipv6_private_networks_exceptions.all(it.contains(a) == false)
}
return ip.is_private()
}
// is_global return true if the address is globally reachable.
pub fn (a Ipv6Addr) is_global() bool {
return !a.is_private()
}
// is_reserved returns true if the address is allocated in reserved networks.
pub fn (a Ipv6Addr) is_reserved() bool {
ip := a.ipv4() or { return ipv6_reserved_networks.any(it.contains(a) == true) }
return ip.is_reserved()
}
// is_unspecified returns true if IP address is unspecified i.e equals ::.
pub fn (a Ipv6Addr) is_unspecified() bool {
ip := a.ipv4() or { return a.addr == [16]u8{} }
return ip.is_unspecified()
}
// is_netmask returns true if IP address is network mask.
pub fn (a Ipv6Addr) is_netmask() bool {
val := a.bigint().bitwise_xor(max_u128) + big.one_int
return val.bitwise_and(val - big.one_int) == big.zero_int
}
// is_hostmask returns true if IP address is host mask.
pub fn (a Ipv6Addr) is_hostmask() bool {
addr_num := a.bigint()
return (addr_num + big.one_int).bitwise_and(addr_num) == big.zero_int
}
// < returns true if a is lesser than b.
pub fn (a Ipv6Addr) < (b Ipv6Addr) bool {
return compare_128(a.addr, b.addr) == -1
}
// == returns true if a equals b.
pub fn (a Ipv6Addr) == (b Ipv6Addr) bool {
return a.addr == b.addr
}
fn split_scope(addr string) !(string, ?string) {
address, zone_id := addr.split_once('%') or { '', 'empty' }
if zone_id == '' || zone_id.contains('%') {
return error('invalid zone_id in ${addr}')
}
if address == '' {
return addr, ?string(none)
}
return address, zone_id
}
@[params]
pub struct Ipv6AddrParams {
pub:
zone_id ?string
}
fn (p Ipv6AddrParams) validate() ! {
if p.zone_id != none {
zone_id := p.zone_id as string
if zone_id.is_blank() || zone_id.contains('%') {
return error('zone_id cannot be blank or contain % sign')
}
}
}
@[flag]
pub enum Ipv6AddrFormat {
compact // e.g. fe80::896:7aff:e87:4ae3
verbose // e.g. fe80:0000:0000:0000:0896:7aff:0e87:4ae3
dotted // use dotted-decimal notation for IPv4-mapped and IPv4-compat addresses e.g. ::ffff:192.168.3.11
}
// TeredoAddr represents the parsed Teredo address. See RFC 4380 Section 4.
pub struct TeredoAddr {
pub:
server Ipv4Addr
flags u16
port u16
client Ipv4Addr
}
// ipv6 returns Ipv6Addr created from Teredo address.
@[direct_array_access]
pub fn (t TeredoAddr) ipv6() Ipv6Addr {
mut addr := [16]u8{}
addr[0] = u8(0x20)
addr[1] = u8(0x01)
mut flags := [2]u8{}
binary.big_endian_put_u16_fixed(mut flags, t.flags)
addr[8] = flags[0]
addr[9] = flags[1]
mut port := [2]u8{}
binary.big_endian_put_u16_fixed(mut port, t.port)
addr[10] = ~port[0]
addr[11] = ~port[1]
for i := 4; i < 8; i++ {
addr[i] = t.server.addr[i - 4]
addr[i + 8] = ~t.client.addr[i - 4]
}
return Ipv6Addr{
addr: addr
}
}
pub struct Ipv6Net {
pub:
network_address Ipv6Addr
network_mask Ipv6Addr
host_mask Ipv6Addr
broadcast_address Ipv6Addr
host_address ?Ipv6Addr
prefix_len int
mut:
current big.Integer
}
// Ipv6Net.new creates new IPv6 network from given Ipv6Addr and prefix.
pub fn Ipv6Net.new(addr Ipv6Addr, prefix int) !Ipv6Net {
if prefix < 0 || prefix > 128 {
return error('prefix length must be in range 0-128, not ${prefix}')
}
mut net_addr := addr
mut host_addr := ?Ipv6Addr(none)
net_mask := Ipv6Addr{
addr: bitwise_xor_128(max_128, right_shift_128(max_128, prefix))
}
if bitwise_and_128(net_addr.addr, net_mask.addr) != net_addr.u8_array_fixed() {
host_addr = Ipv6Addr{
addr: net_addr.addr
}
net_addr = Ipv6Addr{
addr: bitwise_and_128(net_addr.addr, net_mask.addr)
}
}
host_mask := Ipv6Addr{
addr: bitwise_xor_128(net_mask.addr, max_128)
}
broadcast := Ipv6Addr{
addr: bitwise_or_128(net_addr.addr, host_mask.addr)
}
return Ipv6Net{
network_address: net_addr
network_mask: net_mask
host_mask: host_mask
broadcast_address: broadcast
host_address: host_addr
prefix_len: prefix
current: net_addr.bigint()
}
}
// Ipv6Net.from_string parses cidr and creates new Ipv6Net.
// All formats supported by Ipv6Addr.from_string is allowed here.
// See also Ipv4Net.from_string for additional info about parsing strategy and
// supported network/prefix variants.
pub fn Ipv6Net.from_string(cidr string) !Ipv6Net {
net_addr_str, prefix_str := cidr.split_once('/') or { cidr, '128' }
mut net_addr := Ipv6Addr.from_string(net_addr_str)!
mut prefix_len := 0
mut host_mask := Ipv6Addr{}
mut net_mask := Ipv6Addr{
addr: [16]u8{init: 0xff}
}
mut host_addr := ?Ipv6Addr(none)
if prefix_len_u64 := prefix_str.parse_uint(10, 64) {
prefix_len = int(prefix_len_u64)
if prefix_len < 128 {
net_mask = Ipv6Addr{
addr: bitwise_xor_128(max_128, right_shift_128(max_128, prefix_len))
}
}
host_mask = Ipv6Addr{
addr: bitwise_xor_128(net_mask.addr, max_128)
}
} else {
mut mask := Ipv6Addr.from_string(prefix_str)!
match true {
mask.is_netmask() || mask.addr == [16]u8{} || mask.addr == [16]u8{init: 0xff} {
net_mask = mask
host_mask = Ipv6Addr{
addr: bitwise_xor_128(mask.addr, max_128)
}
prefix_len = 128 - host_mask.bit_len()
}
mask.is_hostmask() {
host_mask = mask
prefix_len = 128 - host_mask.bit_len()
if prefix_len < 128 {
net_mask = Ipv6Addr{
addr: bitwise_xor_128(max_128, right_shift_128(max_128, prefix_len))
}
}
}
else {
return error('${mask} is not valid network or host mask in ${cidr}')
}
}
}
if bitwise_and_128(net_addr.addr, net_mask.addr) != net_addr.u8_array_fixed() {
host_addr = Ipv6Addr{
addr: net_addr.u8_array_fixed()
}
net_addr = Ipv6Addr{
addr: bitwise_and_128(net_addr.u8_array_fixed(), net_mask.addr)
}
}
broadcast := Ipv6Addr{
addr: bitwise_or_128(net_addr.addr, host_mask.addr)
}
return Ipv6Net{
network_address: net_addr
network_mask: net_mask
host_mask: host_mask
broadcast_address: broadcast
host_address: host_addr
prefix_len: prefix_len
current: net_addr.bigint()
}
}
// Ipv6Net.from_bigint creates new IPv6 network from given addr and prefix.
// `addr` must fit in 128 bits.
pub fn Ipv6Net.from_bigint(addr big.Integer, prefix int) !Ipv6Net {
if prefix < 0 || prefix > 128 {
return error('prefix length must be in range 0-128, not ${prefix}')
}
if addr.bit_len() > 128 {
return error('${addr} overflows 128 bit')
}
mut host_addr := ?Ipv6Addr(none)
mut net_addr := addr
net_mask := max_u128.bitwise_xor(max_u128.right_shift(u32(prefix)))
if net_addr.bitwise_and(net_mask) != net_addr {
host_addr = Ipv6Addr.from_bigint(net_addr)!
net_addr = net_addr.bitwise_and(net_mask)
}
host_mask := net_mask.bitwise_xor(max_u128)
broadcast := net_addr.bitwise_or(host_mask)
return Ipv6Net{
network_address: Ipv6Addr.from_bigint(net_addr)!
network_mask: Ipv6Addr.from_bigint(net_mask)!
host_mask: Ipv6Addr.from_bigint(host_mask)!
broadcast_address: Ipv6Addr.from_bigint(broadcast)!
host_address: host_addr
prefix_len: prefix
current: net_addr
}
}
// str returns string representation of IPv6 network in CIDR format.
pub fn (n Ipv6Net) str() string {
return n.format(.compact | .dotted | .with_prefix_len)
}
// format returns the IPv6 network as a string formatted according to the fmt rule.
pub fn (n Ipv6Net) format(fmt Ipv6NetFormat) string {
addr_fmt := Ipv6AddrFormat(fmt)
match true {
fmt & .with_prefix_len == .with_prefix_len {
return n.network_address.format(addr_fmt) + '/' + n.prefix_len.str()
}
fmt & .with_network_mask == .with_network_mask {
return n.network_address.format(addr_fmt) + '/' + n.network_mask.format(addr_fmt)
}
fmt & .with_host_mask == .with_host_mask {
return n.network_address.format(addr_fmt) + '/' + n.host_mask.format(addr_fmt)
}
else {
return n.format(fmt | .with_prefix_len)
}
}
}
// capacity returns a total number of addresses in the network.
pub fn (n Ipv6Net) capacity() big.Integer {
return (n.broadcast_address.bigint() - n.network_address.bigint()) + big.one_int
}
// next implements an iterator that iterates over all addresses in network
// including network and broadcast addresses.
// Example:
// ```
// network := netaddr.Ipv6Net.from_string('fe80::/124')!
// for addr in network {
// println(addr)
// }
// ```
pub fn (mut n Ipv6Net) next() ?Ipv6Addr {
if n.current >= n.broadcast_address.bigint() + big.one_int {
return none
}
defer {
n.current = n.current + big.one_int
}
return Ipv6Addr.from_bigint(n.current)!
}
// first returns the first usable host address in network.
pub fn (n Ipv6Net) first() Ipv6Addr {
if n.prefix_len in [127, 128] {
return n.network_address
}
return Ipv6Addr.from_bigint(n.network_address.bigint() + big.one_int) or { panic(err) }
}
// last returns the last usable host address in network.
pub fn (n Ipv6Net) last() Ipv6Addr {
if n.prefix_len in [127, 128] {
return n.broadcast_address
}
return Ipv6Addr.from_bigint(n.broadcast_address.bigint() - big.one_int) or { panic(err) }
}
// nth returns the Nth address in network. Supports negative indexes.
pub fn (n Ipv6Net) nth(num big.Integer) !Ipv6Addr {
mut addr := Ipv6Addr{}
if num >= big.zero_int {
addr = Ipv6Addr.from_bigint(n.network_address.bigint() + num)!
} else {
addr = Ipv6Addr.from_bigint(n.broadcast_address.bigint() + num + big.one_int)!
}
if n.contains(addr) {
return addr
}
return error('unable to get ${num}th address')
}
// contains returns true if IP address is in the network.
pub fn (n Ipv6Net) contains(addr Ipv6Addr) bool {
return n.network_address <= addr && addr <= n.broadcast_address
}
// overlaps returns true if network partly contains in *other*,
// in other words if the networks addresses sets intersect.
pub fn (n Ipv6Net) overlaps(other Ipv6Net) bool {
return other.contains(n.network_address) || (other.contains(n.broadcast_address)
|| (n.contains(other.network_address) || (n.contains(other.broadcast_address))))
}
// subnets returns iterator that iterates over the network subnets partitioned by given *prefix* length.
// Example:
// ```
// network := netaddr.Ipv6Net.from_string('2001:db8:beaf::/56')!
// subnets := network.subnets(64)!
// for subnet in subnets {
// println(subnet)
// }
// ```
pub fn (n Ipv6Net) subnets(prefix int) !Ipv6NetsIterator {
if prefix > 128 || prefix < n.prefix_len {
return error('prefix length must be in range ${n.prefix_len}-128, not ${prefix}')
}
return Ipv6NetsIterator{
prefix_len: prefix
step: (n.host_mask.bigint() + big.one_int).right_shift(u32(prefix - n.prefix_len))
end: n.broadcast_address.bigint()
current: n.network_address.bigint()
}
}
// supernet returns IPv6 network containing the current network.
pub fn (n Ipv6Net) supernet(prefix int) !Ipv6Net {
if prefix < 0 || prefix > n.prefix_len {
return error('prefix length must be in range 0-${n.prefix_len}, not ${prefix}')
}
if prefix == 0 {
return n
}
net_addr := Ipv6Addr{
addr: bitwise_and_128(n.network_address.addr, left_shift_128(n.network_mask.addr,
n.prefix_len - prefix))
}
return Ipv6Net.new(net_addr, prefix)!
}
// is_subnet_of returns true if *other* contains the network.
pub fn (n Ipv6Net) is_subnet_of(other Ipv6Net) bool {
return other.network_address <= n.network_address
&& other.broadcast_address >= n.broadcast_address
}
// is_supernet_of returns true if the network contains *other*.
pub fn (n Ipv6Net) is_supernet_of(other Ipv6Net) bool {
return n.network_address <= other.network_address
&& n.broadcast_address >= other.broadcast_address
}
// is_site_local returns true if the network is site-local.
pub fn (n Ipv6Net) is_site_local() bool {
return n.network_address.is_site_local() && n.broadcast_address.is_site_local()
}
// is_unique_local returns true if the network is unique-local.
pub fn (n Ipv6Net) is_unique_local() bool {
return n.network_address.is_unique_local() && n.broadcast_address.is_unique_local()
}
// is_link_local returns true if the network is link-local.
pub fn (n Ipv6Net) is_link_local() bool {
return n.network_address.is_link_local() && n.broadcast_address.is_link_local()
}
// is_loopback returns true if this is a loopback network.
pub fn (n Ipv6Net) is_loopback() bool {
return n.network_address.is_loopback() && n.broadcast_address.is_loopback()
}
// is_multicast returns true if the network is reserved for multicast use.
pub fn (n Ipv6Net) is_multicast() bool {
return n.network_address.is_multicast() && n.broadcast_address.is_multicast()
}
// is_unicast returns true if the network is unicast.
pub fn (n Ipv6Net) is_unicast() bool {
return !n.is_multicast()
}
// is_private returns true if the network is not globally reachable.
pub fn (n Ipv6Net) is_private() bool {
return n.network_address.is_private() && n.broadcast_address.is_private()
}
// is_global return true if the network is globally reachable.
pub fn (n Ipv6Net) is_global() bool {
return !n.is_private()
}
// is_reserved returns true if the network is reserved.
pub fn (n Ipv6Net) is_reserved() bool {
return n.network_address.is_reserved() && n.broadcast_address.is_reserved()
}
// is_unspecified returns true if the network is ::/0.
pub fn (n Ipv6Net) is_unspecified() bool {
return n.network_address.is_unspecified() && n.broadcast_address.is_unspecified()
}
// < returns true if the network is lesser than other network.
pub fn (n Ipv6Net) < (other Ipv6Net) bool {
if n.network_address != other.network_address {
return n.network_address < other.network_address
}
if n.network_mask != other.network_mask {
return n.network_mask < other.network_mask
}
return false
}
// == returns true if networks equals.
pub fn (n Ipv6Net) == (other Ipv6Net) bool {
return n.network_address == other.network_address && n.network_mask == n.network_mask
}
@[flag]
pub enum Ipv6NetFormat {
compact
verbose
dotted
with_prefix_len
with_host_mask
with_network_mask
}
pub struct Ipv6NetsIterator {
prefix_len int
step big.Integer
end big.Integer
mut:
current big.Integer
}
// next implements the iterator interface for IP network subnets.
pub fn (mut iter Ipv6NetsIterator) next() ?Ipv6Net {
if iter.current >= iter.end + big.one_int {
return none
}
defer {
iter.current += iter.step
}
return Ipv6Net.from_bigint(iter.current, iter.prefix_len)!
}

294
src/ip6_const.v Normal file
View File

@ -0,0 +1,294 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
// This file contains pre-calculated values for IPv6 reserved networks.
// See https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
module netaddr
struct Ipv6Const {
begin [16]u8
end [16]u8
}
fn (n Ipv6Const) contains(addr Ipv6Addr) bool {
// There is: n.begin <= addr && addr <= n.end
return compare_128(n.begin, addr.addr) in [-1, 0] && compare_128(addr.addr, n.end) in [-1, 0]
}
// fec0::/10
const ipv6_site_local_network = Ipv6Const{
begin: [u8(0xfe), 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00]!
end: [u8(0xfe), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff]!
}
// fc00::/7
const ipv6_unique_local_network = Ipv6Const{
begin: [u8(0xfc), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00]!
end: [u8(0xfd), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff]!
}
// fe80::/10
const ipv6_link_local_network = Ipv6Const{
begin: [u8(0xfe), 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00]!
end: [u8(0xfe), 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff]!
}
// ff00::/8
const ipv6_multicast_network = Ipv6Const{
begin: [u8(0xff), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00]!
end: [u8(0xff), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff]!
}
const ipv6_reserved_networks = [
// ::/8
Ipv6Const{
begin: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x00), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 100::/8
Ipv6Const{
begin: [u8(0x01), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x01), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 200::/7
Ipv6Const{
begin: [u8(0x02), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x03), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 400::/6
Ipv6Const{
begin: [u8(0x04), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x07), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 800::/5
Ipv6Const{
begin: [u8(0x08), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x0f), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 1000::/4
Ipv6Const{
begin: [u8(0x10), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x1f), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 4000::/3
Ipv6Const{
begin: [u8(0x40), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x5f), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 6000::/3
Ipv6Const{
begin: [u8(0x60), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x7f), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 8000::/3
Ipv6Const{
begin: [u8(0x80), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x9f), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// a000::/3
Ipv6Const{
begin: [u8(0xa0), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xbf), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// c000::/3
Ipv6Const{
begin: [u8(0xc0), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xdf), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// e000::/4
Ipv6Const{
begin: [u8(0xe0), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xef), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// f000::/5
Ipv6Const{
begin: [u8(0xf0), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xf7), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// f800::/6
Ipv6Const{
begin: [u8(0xf8), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xfb), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// fe00::/9
Ipv6Const{
begin: [u8(0xfe), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xfe), 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
]!
const ipv6_private_networks = [
// ::1/128
Ipv6Const{
begin: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01]!
end: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01]!
},
// ::/128
Ipv6Const{
begin: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
},
// ::ffff:0:0/96
Ipv6Const{
begin: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 64:ff9b:1::/48
Ipv6Const{
begin: [u8(0x00), 0x64, 0xff, 0x9b, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x00), 0x64, 0xff, 0x9b, 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 100::/64
Ipv6Const{
begin: [u8(0x01), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x01), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2001::/23
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2001:db8::/32
Ipv6Const{
begin: [u8(0x20), 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x0d, 0xb8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2002::/16
Ipv6Const{
begin: [u8(0x20), 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 3fff::/20
Ipv6Const{
begin: [u8(0x3f), 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x3f), 0xff, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// fc00::/7 (unique-local)
Ipv6Const{
begin: [u8(0xfc), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xfd), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// fe80::/10 (link-local)
Ipv6Const{
begin: [u8(0xfe), 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xfe), 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
]!
const ipv6_private_networks_exceptions = [
// 2001:1::1/128
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01]!
end: [u8(0x20), 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01]!
},
// 2001:1::2/128
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x02]!
end: [u8(0x20), 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x02]!
},
// 2001:3::/32
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x00, 0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2001:4:112::/48
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x04, 0x01, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x00, 0x04, 0x01, 0x12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2001:20::/28
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x00, 0x2f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2001:30::/28
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x00, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
]!

77
src/ip_const.v Normal file
View File

@ -0,0 +1,77 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
// This file contains pre-calculated values for IPv4 reserved networks.
// See https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
module netaddr
struct Ipv4Const {
begin u32
end u32
}
fn (n Ipv4Const) contains(addr Ipv4Addr) bool {
return n.begin <= addr.u32() && addr.u32() <= n.end
}
// 169.254.0.0/16
const ipv4_link_local_network = Ipv4Const{u32(2851995648), u32(2852061183)}
// 127.0.0.0/8
const ipv4_loopback_network = Ipv4Const{u32(2130706432), u32(2147483647)}
// 224.0.0.0/4
const ipv4_multicast_network = Ipv4Const{u32(3758096384), u32(4026531839)}
// 100.64.0.0/10
const ipv4_public_network = Ipv4Const{u32(1681915904), u32(1686110207)}
// 240.0.0.0/4
const ipv4_reserved_network = Ipv4Const{u32(4026531840), u32(4294967295)}
const ipv4_private_networks = [
// 0.0.0.0/8
Ipv4Const{u32(0), u32(16777215)},
// 10.0.0.0/8
Ipv4Const{u32(167772160), u32(184549375)},
// 169.254.0.0/16
Ipv4Const{u32(2851995648), u32(2852061183)}
// 127.0.0.0/8
Ipv4Const{u32(2130706432), u32(2147483647)}
// 172.16.0.0/12
Ipv4Const{u32(2886729728), u32(2887778303)},
// 192.0.0.0/24
Ipv4Const{u32(3221225472), u32(3221225727)},
// 192.0.0.170/31
Ipv4Const{u32(3221225642), u32(3221225643)},
// 192.0.2.0/24
Ipv4Const{u32(3221225984), u32(3221226239)},
// 192.168.0.0/16
Ipv4Const{u32(3232235520), u32(3232301055)},
// 198.18.0.0/15
Ipv4Const{u32(3323068416), u32(3323199487)},
// 198.51.100.0/24
Ipv4Const{u32(3325256704), u32(3325256959)},
// 203.0.113.0/24
Ipv4Const{u32(3405803776), u32(3405804031)},
// 240.0.0.0/4
Ipv4Const{u32(4026531840), u32(4294967295)}
// 255.255.255.255/32
Ipv4Const{u32(4294967295), u32(4294967295)},
]!
const ipv4_private_networks_exceptions = [
// 192.0.0.9/32
Ipv4Const{u32(3221225481), u32(3221225481)},
// 192.0.0.10/32
Ipv4Const{u32(3221225482), u32(3221225482)},
]!

98
src/sumtypes.v Normal file
View File

@ -0,0 +1,98 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
module netaddr
pub type IpAddr = Ipv4Addr | Ipv4Net | Ipv6Addr | Ipv6Net
// IpAddr.from_string parses the addr string and returns IP address or IP network.
// This is universal function that processes both internet protocol versions.
//
// This function accepts all of the IP address and network formats allowed in
// Ipv4Addr.from_string, Ipv4Net.from_string, Ipv6Addr.from_string
// and Ipv6Net.from_string.
//
// Example:
// ```
// ip := netaddr.IpAddr.from_string('2001:db8:beaf::/56')!
// match ip {
// netaddr.Ipv4Addr {
// println('${ip} is IPv4 address')
// }
// netaddr.Ipv4Net {
// println('${ip} is IPv4 network')
// }
// netaddr.Ipv6Addr {
// println('${ip} is IPv6 address')
// }
// netaddr.Ipv6Net {
// println('${ip} is IPv6 network')
// }
// }
// ```
pub fn IpAddr.from_string(addr string) !IpAddr {
if addr.contains('/') {
if result := Ipv4Net.from_string(addr) {
return result
}
if result := Ipv6Net.from_string(addr) {
return result
}
}
if result := Ipv4Addr.from_string(addr) {
return result
}
if result := Ipv6Addr.from_string(addr) {
return result
}
return error('${addr} is not a valid IPv4 or IPv6 address or network')
}
// str returns the IP string representation.
pub fn (ip IpAddr) str() string {
return match ip {
Ipv4Addr { ip.str() }
Ipv6Addr { ip.str() }
Ipv4Net { ip.str() }
Ipv6Net { ip.str() }
}
}
pub type Eui = Eui48 | Eui64
// Eui.from_string parses addr string and returns EUI-48 or EUI-64.
// Example:
// ```v okfmt
// cmd := os.execute('ip -br link show wlan0')
// interface_id := netaddr.Eui.from_string(cmd.output.split_by_space()[2])!
// println(interface_id)
// ```
pub fn Eui.from_string(addr string) !Eui {
if result := Eui48.from_string(addr) {
return result
}
if result := Eui64.from_string(addr) {
return result
}
return error('${addr} is not valid EUI-48 or EUI-64')
}
// str returns the EUI string representation.
pub fn (eui Eui) str() string {
return match eui {
Eui48 { eui.str() }
Eui64 { eui.str() }
}
}