views:

268

answers:

2

Is it possible to detach a native socket from Boost.ASIO's socket class? If so, how can it be done? I can't seem to find anything obvious in the documentation.

As a quick overview of what I'm trying to accomplish: I have a class that makes a connection and does some negotiation using Boost.ASIO, then passes back a native Windows SOCKET on success or 0 on failure.

Unless I'm mistaken, the native socket will be closed and deallocated when my asio::basic_socket is destructed.

+3  A: 

Answering my own question.

Windows has a WSADuplicateSocket function, which can be used to duplicate the native socket. The underlying socket will remain open until all descriptors for this socket are deallocated.

http://msdn.microsoft.com/en-us/library/ms741565(VS.85).aspx

dauphic
A: 

For Mac OS X do the following (for Linux it isn't hard to modify, just notice the very idea):

  1. Wrap socket in a shared_ptr, so that it won't close when passing into different routines and keep it alive (at least one reference should always exist);
  2. Get a native descriptor with socket.native();
  3. Remove it from kqueue:

    struct kevent event;
    EV_SET(&event, descriptor, EVFILT_READ, EV_DELETE, 0, 0, 0);  //or EVFILT_WRITE
    
  4. And make it blocking if needed:

    fcntl(descriptor, F_SETFL, fcntl(descriptor, F_GETFL, 0) & ~O_NONBLOCK);
    
iUm
I know its not exactly obvious but code following list elements needs 8 spaces indentation - see [here](http://meta.stackoverflow.com/questions/24424/list-preceeding-code-prevents-code-from-being-displayed-as-code).
Georg Fritzsche