packages feed

concurrent-dns-cache-0.1.4: Network/DNS/Cache/Utils.hs

module Network.DNS.Cache.Utils where

import qualified Data.ByteString.Char8 as BS
import Data.Char (isDigit)
import Data.IP (toHostAddress, toIPv4)
import Network.DNS.Cache.Types

-- | Parsing a dotted-decimal IPv4 address strictly.
--   Groups with leading zeros are rejected since they may be octal.
parseIPv4 :: Domain -> Maybe HostAddress
parseIPv4 hn = case mapM octet (BS.split '.' hn) of
    Just [a, b, c, d] -> Just $ toHostAddress $ toIPv4 [a, b, c, d]
    _ -> Nothing
  where
    octet x
        | BS.null x || BS.length x > 3 = Nothing
        | not (BS.all isDigit x) = Nothing
        | BS.length x > 1 && BS.head x == '0' = Nothing
        | otherwise = let n = read (BS.unpack x)
                      in if n <= 255 then Just n else Nothing

fromResult :: Result -> HostAddress
fromResult (Hit      addr) = addr
fromResult (Resolved addr) = addr
fromResult (Numeric  addr) = addr

fromEither :: Either DNSError Result -> Maybe HostAddress
fromEither (Right res) = Just (fromResult res)
fromEither (Left    _) = Nothing