From 7f1c5a928e3addbd3af7b40ed825b0423e900b68 Mon Sep 17 00:00:00 2001 From: John Ky Date: Fri, 3 May 2024 21:06:52 +1000 Subject: [PATCH] Allow the port to be reused immediately after it is closed --- src/Hedgehog/Extras/Stock/IO/Network/Port.hs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Hedgehog/Extras/Stock/IO/Network/Port.hs b/src/Hedgehog/Extras/Stock/IO/Network/Port.hs index 67c158fc..52b967df 100644 --- a/src/Hedgehog/Extras/Stock/IO/Network/Port.hs +++ b/src/Hedgehog/Extras/Stock/IO/Network/Port.hs @@ -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 @@ -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 @@ -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