Skip to content

Commit

Permalink
Allow the port to be reused immediately after it is closed
Browse files Browse the repository at this point in the history
  • Loading branch information
newhoggy committed May 3, 2024
1 parent 285f1df commit c811275
Showing 1 changed file with 4 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Hedgehog/Extras/Stock/IO/Network/Port.hs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ randomPort :: ()
-> m PortNumber
randomPort hostAddress = do
sock <- liftIO $ socket AF_INET Stream defaultProtocol
-- Allow the port to be reused immediately after the socket is closed
liftIO $ setSocketOption sock ReuseAddr 1
liftIO $ bind sock $ SockAddrInet defaultPort hostAddress
SockAddrInet port _ <- liftIO $ getSocketName sock
liftIO $ close sock
Expand All @@ -35,6 +37,7 @@ reserveRandomPort :: ()
-> m (ReleaseKey, PortNumber)
reserveRandomPort hostAddress = do
sock <- liftIO $ socket AF_INET Stream defaultProtocol
liftIO $ setSocketOption sock ReuseAddr 1
liftIO $ bind sock $ SockAddrInet defaultPort hostAddress
SockAddrInet port _ <- liftIO $ getSocketName sock
releaseKey <- register $ close sock
Expand All @@ -48,6 +51,7 @@ portInUse :: ()
-> m Bool
portInUse hostAddress pn = do
sock <- liftIO $ socket AF_INET Stream defaultProtocol
liftIO $ setSocketOption sock ReuseAddr 1
result <- liftIO $ try @SomeException $ bind sock (SockAddrInet pn hostAddress)
liftIO $ close sock
return $ either (const False) (const True) result

0 comments on commit c811275

Please sign in to comment.