module Cidr ( Cidr(..), cidr_from_string, is_valid_cidr ) where import Text.Regex.Posix import IPv4Address import ListUtils import Octet data Cidr = Cidr { ipv4address :: IPv4Address, maskbits :: Maskbits } deriving (Eq, Show) -- Will return True if the passed String is in CIDR notation, False -- otherwise. is_valid_cidr :: String -> Bool is_valid_cidr cidr = cidr =~ "([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}" -- Returns the mask portion of a CIDR address. That is, everything -- after the trailing slash. maskbits_from_string :: String -> Maskbits maskbits_from_string s = read ((splitWith (`elem` "/") s) !! 1) -- Takes an IP address String in CIDR notation, and returns a list of -- its octets (as Ints). octets_from_string :: String -> [Int] octets_from_string s = map read (take 4 (splitWith (`elem` "./") s)) cidr_from_string :: String -> Cidr cidr_from_string s = Cidr addr mbits where addr = IPv4Address (oct1) (oct2) (oct3) (oct4) oct1 = octet_from_int (octs !! 0) oct2 = octet_from_int (octs !! 1) oct3 = octet_from_int (octs !! 2) oct4 = octet_from_int (octs !! 3) octs = octets_from_string s mbits = maskbits_from_string s