Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass socket handle from .NET to unmanaged child process

I currently have a .NET program initiating a connection to a server and starting another, unmanaged executable. The native process should take over the same socket (it is essential for the connection not to be closed until the termination of the child process!) and start communicating through it with the server.

The aforementioned programs run both on Windows, however I'd prefer a solution that does not involve P/Invoke for the .NET part. As a side note, communication from parent to child process is not an issue so I can easily share data between the two.
Furthermore, once I start using the socket from the native process I don't need to use it from the .NET process anymore and the .NET process will terminate before I'm done using the socket from the unmanaged process, thus along with the solution I need to know what to do with the Socket object in .NET so that its disposal doesn't affect the OS socket and its usability.

Thanks in advance!

like image 449
em70 Avatar asked Jan 05 '11 13:01

em70


1 Answers

.NET 2.0 and later offers handy method DuplicateAndClose.

Upd: looks like a hack will be needed to find out where (at which offset) in SocketInformation.ProtocolInformation the destination socket is stored. This can be done by capturing the byte array in the source process, then re-creating a socket in another .NET process and getting the socket handle there (in that second process). Then look where the data is in the byte array.

Also there's a good unmanaged way to duplicate sockets, described here.

like image 118
Eugene Mayevski 'Callback Avatar answered Sep 22 '22 11:09

Eugene Mayevski 'Callback