diff options
author | Roman Smrž <roman.smrz@seznam.cz> | 2023-03-30 22:31:30 +0200 |
---|---|---|
committer | Roman Smrž <roman.smrz@seznam.cz> | 2023-03-31 21:46:35 +0200 |
commit | 4b308cb9edb5a564ef33d6c6739305085dfa9ebb (patch) | |
tree | e5854787c3aff009952bc8d03d86fd7ba39cfcc8 /src/Network | |
parent | 29943f6ade81579586218a57b2440fe7fa4131cc (diff) |
Types for IP address and prefix
Diffstat (limited to 'src/Network')
-rw-r--r-- | src/Network/Ip.hs | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/src/Network/Ip.hs b/src/Network/Ip.hs new file mode 100644 index 0000000..76cc8f4 --- /dev/null +++ b/src/Network/Ip.hs @@ -0,0 +1,45 @@ +module Network.Ip ( + IpPrefix(..), + textIpNetwork, + + IpAddress(..), + textIpAddress, + textIpAddressCidr, + + allowsSubnets, + ipSubnet, + lanSubnet, +) where + +import Data.Text (Text) +import Data.Text qualified as T +import Data.Word + +newtype IpPrefix = IpPrefix [Word8] + deriving (Eq, Ord) + +textIpNetwork :: IpPrefix -> Text +textIpNetwork (IpPrefix prefix) = + T.intercalate "." (map (T.pack . show) $ prefix ++ replicate (4 - length prefix) 0) + <> "/" <> T.pack (show (8 * length prefix)) + +data IpAddress = IpAddress IpPrefix Word8 + deriving (Eq, Ord) + +textIpAddress :: IpAddress -> Text +textIpAddress (IpAddress (IpPrefix prefix) num) = + T.intercalate "." $ map (T.pack . show) $ prefix ++ replicate (3 - length prefix) 0 ++ [num] + +textIpAddressCidr :: IpAddress -> Text +textIpAddressCidr ip@(IpAddress (IpPrefix prefix) _) = + textIpAddress ip <> "/" <> T.pack (show (8 * length prefix)) + +allowsSubnets :: IpPrefix -> Bool +allowsSubnets (IpPrefix prefix) = length prefix < 3 + +ipSubnet :: Word8 -> IpPrefix -> IpPrefix +ipSubnet num (IpPrefix prefix) = IpPrefix (prefix ++ [num]) + +lanSubnet :: IpPrefix -> IpPrefix +lanSubnet (IpPrefix prefix) = IpPrefix (take 3 $ prefix ++ repeat 0) + |