Getting the first available port in Haskell, in a platform-independent way

Viewed 309

I'd like to get the first available (unbound) port to be able to start a connection on it. Right now I'm using the bind function in the following way:

-- | Get a free port number.
getFreePort :: IO Integer
getFreePort = do
  sock <- socket AF_INET Stream defaultProtocol
  bind sock (SockAddrInet aNY_PORT iNADDR_ANY)
  port <- socketPort  sock
  close sock
  return (toInteger port)

But I'm not sure about the parameters I'm passing to socket and bind, and I also have to bind the socket only to extract its number and then close it again, which seems like a bit of overhead.

Can this be achieved in a better way?

0 Answers
Related