将套接字句柄从.NET传递到非托管子进程 [英] Pass socket handle from .NET to unmanaged child process

查看:46
本文介绍了将套接字句柄从.NET传递到非托管子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个.NET程序,用于启动与服务器的连接并启动另一个不受管理的可执行文件.本机进程应该接管相同的套接字(这对于在子进程终止之前不关闭连接至关重要!)并开始通过该套接字与服务器进行通信.

上述程序都可以在Windows上运行,但是我更喜欢一个不涉及.NET部分P/Invoke的解决方案.附带说明一下,从父进程到子进程的通信不是问题,因此我可以轻松地在两者之间共享数据.
此外,一旦我开始使用本机进程中的套接字,就不再需要使用.NET进程中的套接字,并且.NET进程 将在我完成使用.so中的套接字之前终止.非托管进程,因此,与解决方案一起,我需要知道如何处理.NET中的Socket对象,以便其处理不会影响OS套接字及其可用性.

提前谢谢!

解决方案

.NET 2.0和更高版本提供了便捷的方法此处所述./p>

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!

解决方案

.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.

这篇关于将套接字句柄从.NET传递到非托管子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆