Skip to content

Commit

Permalink
Supporting socket2fd on Windows
Browse files Browse the repository at this point in the history
Credit: Tamar Christina <tamar@zhox.com>
  • Loading branch information
kazu-yamamoto committed Sep 17, 2019
1 parent d0bba03 commit 27d9815
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Network/Socket/Types.hsc
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,16 @@ withFdSocket (Socket ref _) f = do
-- duplicated file descriptor.
socketToFd :: Socket -> IO CInt
socketToFd s = do
#if defined(mingw32_HOST_OS)
fd <- unsafeFdSocket s
fd2 <- c_wsaDuplicate fd
-- FIXME: throw error no if -1
close s
return fd2

foreign import ccall unsafe "wsaDuplicate"
c_wsaDuplicate :: CInt -> IO CInt
#else
fd <- unsafeFdSocket s
-- FIXME: throw error no if -1
fd2 <- c_dup fd
Expand All @@ -182,6 +192,7 @@ socketToFd s = do

foreign import ccall unsafe "dup"
c_dup :: CInt -> IO CInt
#endif

-- | Creating a socket from a file descriptor.
mkSocket :: CInt -> IO Socket
Expand Down
15 changes: 15 additions & 0 deletions cbits/initWinSock.c
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,19 @@ initWinSock ()
return 0;
}

SOCKET
wsaDuplicate (SOCKET s)
{
WSAPROTOCOL_INFOW protocolInfo;
if (WSADuplicateSocketW (s, GetCurrentProcessId (), &protocolInfo) != 0)
return -1;

SOCKET res = WSASocketW(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
FROM_PROTOCOL_INFO, &protocolInfo, 0, 0);
if (res == SOCKET_ERROR)
return -1;

return res;
}

#endif
10 changes: 10 additions & 0 deletions tests/Network/SocketSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,13 @@ spec = do
threadDelay 10000
void $ recv sock 1024
tcpTest client server

describe "socketToFd" $ do
it "socketToFd can send using fd" $ do
let server sock = do
void $ recv sock 1024
client sock = do
fd <- socketToFd sock
s <- mkSocket fd
sendAll s "HELLO WORLD"
tcpTest client server

0 comments on commit 27d9815

Please sign in to comment.