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
@type network() :: {:inet.ip_address(), 0..128}
Functions
Formats a network as a CIDR string.
iex> Sovite.Net.format_cidr({{0x2001, 0xDB8, 0, 0, 0, 0, 0, 0}, 32})
"2001:db8::/32"
@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
@spec in_networks?(:inet.ip_address(), [network()]) :: boolean()
Returns true if ip is in any of networks.
@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.
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}
@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}