| 1 |
{-# LANGUAGE BangPatterns #-} |
| 2 |
{-# LANGUAGE DeriveDataTypeable #-} |
| 3 |
{-# LANGUAGE OverloadedStrings #-} |
| 4 |
|
| 5 |
module System.IO.Streams.Network.Internal.Address |
| 6 |
( getSockAddr |
| 7 |
, getSockAddrImpl |
| 8 |
, AddressNotSupportedException(..) |
| 9 |
) where |
| 10 |
|
| 11 |
------------------------------------------------------------------------------ |
| 12 |
import Control.Exception (Exception, throwIO) |
| 13 |
import Data.ByteString.Char8 (ByteString) |
| 14 |
import qualified Data.ByteString.Char8 as S |
| 15 |
import Data.Typeable (Typeable) |
| 16 |
import Network.Socket (AddrInfo (addrAddress, addrFamily, addrFlags), AddrInfoFlag (AI_NUMERICSERV), Family, SockAddr, defaultHints, getAddrInfo) |
| 17 |
|
| 18 |
|
| 19 |
------------------------------------------------------------------------------ |
| 20 |
data AddressNotSupportedException = AddressNotSupportedException String |
| 21 |
deriving (Typeable) |
| 22 |
|
| 23 |
instance Show AddressNotSupportedException where |
| 24 |
show (AddressNotSupportedException x) = "Address not supported: " ++ x |
| 25 |
|
| 26 |
instance Exception AddressNotSupportedException |
| 27 |
|
| 28 |
------------------------------------------------------------------------------ |
| 29 |
getSockAddr :: Int |
| 30 |
-> ByteString |
| 31 |
-> IO (Family, SockAddr) |
| 32 |
getSockAddr = getSockAddrImpl getAddrInfo |
| 33 |
|
| 34 |
|
| 35 |
------------------------------------------------------------------------------ |
| 36 |
getSockAddrImpl |
| 37 |
:: (Maybe AddrInfo -> Maybe String -> Maybe String -> IO [AddrInfo]) |
| 38 |
-> Int -> ByteString -> IO (Family, SockAddr) |
| 39 |
getSockAddrImpl !_getAddrInfo p s = do |
| 40 |
ais <- _getAddrInfo (Just hints) (Just $ S.unpack s) |
| 41 |
(Just $ show p) |
| 42 |
if null ais |
| 43 |
then throwIO $ AddressNotSupportedException $ show s |
| 44 |
else do |
| 45 |
let !ai = head ais |
| 46 |
let !fm = addrFamily ai |
| 47 |
let !sa = addrAddress ai |
| 48 |
return (fm, sa) |
| 49 |
where |
| 50 |
hints = defaultHints { addrFlags = [AI_NUMERICSERV] } |