Skip to content

Commit 94436bb

Browse files
committed
defining SocketTimeout
1 parent 0ede619 commit 94436bb

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Network/Socket/Options.hsc

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ import Network.Socket.Internal
3838
import Network.Socket.Types
3939
import Network.Socket.ReadShow
4040

41+
#include <sys/time.h>
42+
4143
----------------------------------------------------------------
4244
-- Socket Properties
4345

@@ -386,6 +388,8 @@ setSocketOption s so@Linger v = do
386388
let arg = if v == 0 then StructLinger 0 0 else StructLinger 1 (fromIntegral v)
387389
setSockOpt s so arg
388390
#endif
391+
setSocketOption s so@RecvTimeOut v = setSockOpt s so $ SocketTimeout $ fromIntegral v
392+
setSocketOption s so@SendTimeOut v = setSockOpt s so $ SocketTimeout $ fromIntegral v
389393
setSocketOption s sa v = setSockOpt s sa (fromIntegral v :: CInt)
390394

391395
-- | Set a socket option.
@@ -412,6 +416,12 @@ getSocketOption s so@Linger = do
412416
StructLinger onoff linger <- getSockOpt s so
413417
return $ fromIntegral $ if onoff == 0 then 0 else linger
414418
#endif
419+
getSocketOption s so@RecvTimeOut = do
420+
SocketTimeout to <- getSockOpt s so
421+
return $ fromIntegral to
422+
getSocketOption s so@SendTimeOut = do
423+
SocketTimeout to <- getSockOpt s so
424+
return $ fromIntegral to
415425
getSocketOption s so = do
416426
n :: CInt <- getSockOpt s so
417427
return $ fromIntegral n
@@ -470,6 +480,33 @@ instance Storable StructLinger where
470480

471481
----------------------------------------------------------------
472482

483+
-- | Timeout in microseconds.
484+
newtype SocketTimeout = SocketTimeout Word32 deriving (Eq, Ord, Show)
485+
486+
#if defined(mingw32_HOST_OS)
487+
instance Storable SocketTimeout where
488+
sizeOf (SocketTimeout to) = sizeOf to -- DWORD as milliseconds
489+
alignment _ = 0
490+
peek ptr = do
491+
to <- peek (castPtr ptr)
492+
return $ SocketTimeout (to * 1000)
493+
poke ptr (SocketTimeout to) = poke (castPtr ptr) (to `div` 1000)
494+
#else
495+
instance Storable SocketTimeout where
496+
sizeOf _ = (#size struct timeval)
497+
alignment _ = (#const offsetof(struct {char x__; struct timeval (y__); }, y__))
498+
peek ptr = do
499+
sec <- (#peek struct timeval, tv_sec) ptr
500+
usec <- (#peek struct timeval, tv_usec) ptr
501+
return $ SocketTimeout (sec * 1000000 + usec)
502+
poke ptr (SocketTimeout to) = do
503+
let (sec, usec) = to `divMod` 1000000
504+
(#poke struct timeval, tv_sec) ptr sec
505+
(#poke struct timeval, tv_usec) ptr usec
506+
#endif
507+
508+
----------------------------------------------------------------
509+
473510
foreign import CALLCONV unsafe "getsockopt"
474511
c_getsockopt :: CInt -> CInt -> CInt -> Ptr a -> Ptr CInt -> IO CInt
475512
foreign import CALLCONV unsafe "setsockopt"

0 commit comments

Comments
 (0)