Sovite.Net (sovite v0.2.0)

Copy Markdown View Source

IP address and CIDR network helpers.

All functions are pure and never raise on bad input. Addresses are :inet tuples. A network is {address, prefix_length}.

Summary

Functions

Formats a network as a CIDR string.

Returns true if ip is in network. IPv4-mapped IPv6 addresses match IPv4 networks.

Returns true if ip is in any of networks.

Converts an IPv4-mapped IPv6 address (::ffff:192.0.2.1), as seen on dual-stack sockets, to its IPv4 address. Other addresses are returned unchanged.

Parses a network in CIDR notation. A bare address is a single-host network. Addresses with bits set past the prefix are rejected, since they are usually typos.

Parses an IP address string.

Types

network()

@type network() :: {:inet.ip_address(), 0..128}

Functions

format_cidr(arg)

@spec format_cidr(network()) :: String.t()

Formats a network as a CIDR string.

iex> Sovite.Net.format_cidr({{0x2001, 0xDB8, 0, 0, 0, 0, 0, 0}, 32})
"2001:db8::/32"

in_network?(ip, arg)

@spec in_network?(:inet.ip_address(), network()) :: boolean()

Returns true if ip is in network. IPv4-mapped IPv6 addresses match IPv4 networks.

iex> Sovite.Net.in_network?({192, 0, 2, 7}, {{192, 0, 2, 0}, 24})
true
iex> Sovite.Net.in_network?({0, 0, 0, 0, 0, 0xFFFF, 0xC000, 0x0207}, {{192, 0, 2, 0}, 24})
true

in_networks?(ip, networks)

@spec in_networks?(:inet.ip_address(), [network()]) :: boolean()

Returns true if ip is in any of networks.

normalize(ip)

@spec normalize(:inet.ip_address()) :: :inet.ip_address()

Converts an IPv4-mapped IPv6 address (::ffff:192.0.2.1), as seen on dual-stack sockets, to its IPv4 address. Other addresses are returned unchanged.

parse_cidr(string)

@spec parse_cidr(term()) ::
  {:ok, network()} | {:error, :invalid_cidr | :host_bits_set}

Parses a network in CIDR notation. A bare address is a single-host network. Addresses with bits set past the prefix are rejected, since they are usually typos.

iex> Sovite.Net.parse_cidr("192.0.2.0/24")
{:ok, {{192, 0, 2, 0}, 24}}
iex> Sovite.Net.parse_cidr("::1")
{:ok, {{0, 0, 0, 0, 0, 0, 0, 1}, 128}}
iex> Sovite.Net.parse_cidr("192.0.2.1/24")
{:error, :host_bits_set}

parse_ip(string)

@spec parse_ip(term()) :: {:ok, :inet.ip_address()} | {:error, :invalid_ip}

Parses an IP address string.

iex> Sovite.Net.parse_ip("192.0.2.1")
{:ok, {192, 0, 2, 1}}
iex> Sovite.Net.parse_ip("2001:db8::1")
{:ok, {8193, 3512, 0, 0, 0, 0, 0, 1}}
iex> Sovite.Net.parse_ip("192.0.2")
{:error, :invalid_ip}