on d689c19 help sign in
41 lines 1.3 kB history raw
1{-|
2Module : Util.Net
3Description : Utilities for Network IO.
5License : BSD3
6Maintainer : The Idris Community.
7-}
8module Util.Net (listenOnLocalhost, listenOnLocalhostAnyPort) where
10import Control.Exception (bracketOnError)
11import Network.Socket
12-- Copied from upstream impl of listenOn
13-- bound to localhost interface instead of iNADDR_ANY
14listenOnLocalhost :: PortNumber -> IO Socket
15listenOnLocalhost port = do
16 let hints = defaultHints { addrSocketType = Stream }
17 localhost:_ <- getAddrInfo (Just hints) (Just "127.0.0.1") (Just $ show port)
18 bracketOnError
19 (socket AF_INET Stream defaultProtocol)
20 (close)
21 (\sock -> do
22 setSocketOption sock ReuseAddr 1
23 bind sock (addrAddress localhost)
24 listen sock maxListenQueue
25 return sock
26 )
28listenOnLocalhostAnyPort :: IO (Socket, PortNumber)
29listenOnLocalhostAnyPort = do
30 let hints = defaultHints { addrSocketType = Stream }
31 localhost:_ <- getAddrInfo (Just hints) (Just "127.0.0.1") (Just "0")
32 bracketOnError
33 (socket AF_INET Stream defaultProtocol)
34 (close)
35 (\sock -> do
36 setSocketOption sock ReuseAddr 1
37 bind sock (addrAddress localhost)
38 listen sock maxListenQueue
39 port <- socketPort sock
40 return (sock, port)
41 )