Copyright | © 2018-2020 IOHK |
---|---|
License | Apache-2.0 |
Safe Haskell | None |
Language | Haskell2010 |
Provides functions for checking if TCP ports can be connected to, or are available to listen on.
These can be used for: - Waiting until a server in another process has started. - Start servers for testing when there may be multiple test suites running in parallel.
Synopsis
- data PortNumber
- getRandomPort :: IO PortNumber
- isPortOpen :: SockAddr -> IO Bool
- simpleSockAddr :: ( Word8 , Word8 , Word8 , Word8 ) -> PortNumber -> SockAddr
- portFromURL :: URI -> PortNumber
- randomUnusedTCPPorts :: Int -> IO [ Int ]
Allocation
data PortNumber Source #
Port number.
Use the
Num
instance (i.e. use a literal) to create a
PortNumber
value.
>>>
1 :: PortNumber
1>>>
read "1" :: PortNumber
1>>>
show (12345 :: PortNumber)
"12345">>>
50000 < (51000 :: PortNumber)
True>>>
50000 < (52000 :: PortNumber)
True>>>
50000 + (10000 :: PortNumber)
60000
Instances
getRandomPort :: IO PortNumber Source #
Find a TCPv4 port which is likely to be free for listening on
localhost
. This binds a socket, receives an OS-assigned port, then closes
the socket.
Note that this is vulnerable to race conditions if another process binds the
port returned by
getRandomPort
before this process does.
Do not use this unless you have no other option.
Status
isPortOpen :: SockAddr -> IO Bool Source #
Checks whether
connect()
to a given TCPv4
SockAddr
succeeds or
returns
eCONNREFUSED
.
Rethrows connection exceptions in all other cases (e.g. when the host is unroutable).
Code courtesy of nh2: https://stackoverflow.com/a/57022572
simpleSockAddr :: ( Word8 , Word8 , Word8 , Word8 ) -> PortNumber -> SockAddr Source #
Creates a
SockAttr
from host IP and port number.
Example: > simpleSockAddr (127,0,0,1) 8000
Helpers
portFromURL :: URI -> PortNumber Source #
Get the port from a URI, which is assumed to be a HTTP or HTTPS URL.
randomUnusedTCPPorts :: Int -> IO [ Int ] Source #
Get a list of random TCPv4 ports that currently do not have any servers listening on them. It may return less than the requested number of ports.
Note that this method of allocating ports is subject to race conditions. Production code should use better methods such as passing a listening socket to the child process.