Skip socket handle from .NET to unmanaged child process

Currently, I have a .NET program that initiates a connection to the server and launch another unmanaged executable. The native process must use the same socket (it is important that the connection does not close before the end of the child process!) And begins to exchange it with the server.

The above programs run like on Windows, but I would prefer a solution that does not include P / Invoke for the .NET part. As a side note, communication from parent to child process is not a problem, so I can easily exchange data between them.
In addition, as soon as I start using a socket from my own process, I no longer need to use it from a .NET process, and the .NET process ends before I do this using a socket from an unmanaged process, thus Solution. I need to know what to do with a Socket object in .NET, so removing it does not affect the OS socket and its usability.

Thanks in advance!

+6
c # sockets winsock
source share
2 answers

.NET 2.0 and later offer the convenient DuplicateAndClose method.

Update: looks like a hack to find out where (at what offset) in the SocketInformation.ProtocolInformation the destination socket is stored. This can be done by capturing an array of bytes in the source process, then re-creating the socket in another .NET process and receiving the socket handle (in this second process). Then look where the data is in the byte array.

There is also a good unmanaged way of duplicating sockets, described here .

+4
source share

I think socket descriptors created by the .NET Socket class are inherited by default. IIRC If you create a child process using Process.Start and ProcessStartInfo.UseShellExecute = false (ShellExecute does not allow descriptor inheritance), your child process must already inherit the socket descriptor. Did you try to just pass Socket.Handle to a child process and use it there? And I think that as long as the child process owns the inherited descriptor, the socket remains open, even after the process that created it has disappeared. (I never used this directly, but I once had an average error resulting from this behavior.) However, the socket could be opened with flags like FILE_FLAG_OVERLAPPED etc., and you would need to use the right combination of functions .

0
source share

All Articles