From 07821494dd3d1e0fac75fd01d5596bcb076022ae Mon Sep 17 00:00:00 2001 From: Eishun Kondoh Date: Tue, 9 Oct 2018 14:04:22 +0900 Subject: [PATCH] tres/ipv4_address: Add a function for network address calculation helper --- lib/tres/ipv4_address.ex | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lib/tres/ipv4_address.ex b/lib/tres/ipv4_address.ex index 202fa77..3bc4e42 100644 --- a/lib/tres/ipv4_address.ex +++ b/lib/tres/ipv4_address.ex @@ -27,6 +27,18 @@ defmodule Tres.IPv4Address do end end + @doc """ + iex> addr = IPv4Address.parse("192.168.10.1/24") + iex> {192, 168, 10, 0} = IPv4Address.to_network(addr) + """ + @spec to_network({in_addr(), in_addr()}) :: in_addr() + def to_network({{a1, a2, a3, a4}, {m1, m2, m3, m4}}) do + addr_int = :binary.decode_unsigned(<>, :big) + mask_int = :binary.decode_unsigned(<>, :big) + <> = <<(addr_int &&& mask_int)::32>> + {n1, n2, n3, n4} + end + @doc """ iex> "192.168.0.1" = IPv4Address.to_str({192, 168, 0, 1}) """