How to convert IntPtr / Int to Socket?

I want to convert message.WParam to Socket.

protected override void WndProc(ref Message m) { if (m.Msg == Values.MESSAGE_ASYNC) { switch (m.LParam.ToInt32()) { case Values.FD_READ: WS2.Receive(m.WParam); case Values.FD_WRITE: break; default: break; } } else { base.WndProc(ref m); } } public class WS2 { public static void Receive(IntPtr sock) { Socket socket = sock; } } 

How to convert IntrPtr (sock) to Socket so that I can call Receive ()?

+4
source share
2 answers

You cannot do this because the Socket class creates and manages its own descriptor descriptor. In theory, you could use some kind of evil reflection to plug your socket descriptor into a private Socket field, but that’s a common hack and I wouldn’t.

If the correct socket descriptor is specified, you can receive data by calling the Win32 return function via P / Invoke, for example:

 [DllImport("ws2_32.dll")] extern static int recv([In] IntPtr socketHandle, [In] IntPtr buffer, [In] int count, [In] SocketFlags socketFlags); /// <summary> /// Receives data from a socket. /// </summary> /// <param name="socketHandle">The socket handle.</param> /// <param name="buffer">The buffer to receive.</param> /// <param name="offset">The offset within the buffer.</param> /// <param name="size">The number of bytes to receive.</param> /// <param name="socketFlags">The socket flags.</param> /// <exception cref="ArgumentException">If <paramref name="socketHandle"/> /// is zero.</exception> /// <exception cref="ArgumentNullException">If <paramref name="buffer"/> /// is null.</exception> /// <exception cref="ArgumentOutOfRangeException">If the /// <paramref name="offset"/> and <paramref name="size"/> specify a range /// outside the given buffer.</exception> public static int Receive(IntPtr socketHandle, byte[] buffer, int offset, int size, SocketFlags socketFlags) { if (socketHandle == IntPtr.Zero) throw new ArgumentException("socket"); if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || offset >= buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (size < 0 || offset + size > buffer.Length) throw new ArgumentOutOfRangeException("size"); unsafe { fixed (byte* pData = buffer) { return Recv(socketHandle, new IntPtr(pData + offset), size, socketFlags); } } } 
+6
source

Nothing exists in the Socket class , but the API is used for this, and the Handle property is read-only.

You will probably be best off just P / Invoking recv and call it directly using the IntPtr descriptor.

Quick look The rotor code looks like you could get off creating a Socket, closing the handle , and then setting its m_handle field to your own. But this requires Reflection, and if your socket is already connected (as it sounds, since you just asked about the recv call), you will also have to manipulate the private state of the Socket, which makes this idea even less acceptable and more fragile.

+1
source

All Articles