]> gitweb.michael.orlitzky.com - hath.git/blob - src/Cidr.hs
4bb3d48ef788656c79abf8f971a46f07f1a3a48d
[hath.git] / src / Cidr.hs
1 module Cidr
2 ( Cidr(..),
3 cidr_from_string,
4 is_valid_cidr
5 ) where
6
7 import Text.Regex.Posix
8
9 import IPv4Address
10 import ListUtils
11 import Octet
12
13
14 data Cidr = None | Cidr { ipv4address :: IPv4Address,
15 maskbits :: Maskbits }
16 deriving (Eq, Show)
17
18 -- Will return True if the passed String is in CIDR notation, False
19 -- otherwise.
20 is_valid_cidr :: String -> Bool
21 is_valid_cidr cidr = cidr =~ "([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}"
22
23
24 -- Returns the mask portion of a CIDR address. That is, everything
25 -- after the trailing slash.
26 maskbits_from_string :: String -> Maskbits
27 maskbits_from_string s = read ((splitWith (`elem` "/") s) !! 1)
28
29
30 -- Takes an IP address String in CIDR notation, and returns a list of
31 -- its octets (as Ints).
32 octets_from_string :: String -> [Int]
33 octets_from_string s = map read (take 4 (splitWith (`elem` "./") s))
34
35
36 cidr_from_string :: String -> Cidr
37 cidr_from_string s
38 | addr == IPv4Address.None = Cidr.None
39 | otherwise = Cidr addr mbits
40 where
41 addr = ipv4address_from_octets (oct1) (oct2) (oct3) (oct4)
42 oct1 = octet_from_int (octs !! 0)
43 oct2 = octet_from_int (octs !! 1)
44 oct3 = octet_from_int (octs !! 2)
45 oct4 = octet_from_int (octs !! 3)
46 octs = octets_from_string s
47 mbits = maskbits_from_string s