Skip to content

Commit

Permalink
implementing socketPortSafe (haskell#319).
Browse files Browse the repository at this point in the history
  • Loading branch information
kazu-yamamoto committed May 25, 2018
1 parent f48aab4 commit abfddc8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions Network/Socket.hs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ module Network.Socket
-- ** Port number
, PortNumber
, defaultPort
, socketPortSafe
, socketPort

-- * UNIX-domain socket
Expand Down
13 changes: 13 additions & 0 deletions Network/Socket/Name.hs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module Network.Socket.Name (
getPeerName
, getSocketName
, socketPort
, socketPortSafe
) where

import Foreign.Marshal.Utils (with)
Expand Down Expand Up @@ -48,6 +49,7 @@ foreign import CALLCONV unsafe "getsockname"
-- was given $aNY\_PORT$.

-- | Getting the port of socket.
-- `IOError` is thrown if a port is not available.
socketPort :: Socket -- Connected & Bound Socket
-> IO PortNumber -- Port Number of Socket
socketPort s = do
Expand All @@ -57,3 +59,14 @@ socketPort s = do
SockAddrInet6 port _ _ _ -> return port
_ -> ioError $ userError "Network.Socket.socketPort: AF_UNIX not supported."

-- ---------------------------------------------------------------------------
-- socketPortSafe
-- | Getting the port of socket.
socketPortSafe :: Socket -- Connected & Bound Socket
-> IO (Maybe PortNumber) -- Port Number of Socket
socketPortSafe s = do
sa <- getSocketName s
return $ case sa of
SockAddrInet port _ -> Just port
SockAddrInet6 port _ _ _ -> Just port
_ -> Nothing

0 comments on commit abfddc8

Please sign in to comment.