Question

Here is my code which I had no success with:

Unmanaged.WsaBuf buffer =
    Unmanaged.WsaBuf.Create("Blah Blah");

IntPtr bufferPointer = Marshal.AllocHGlobal(Marshal.SizeOf(buffer));
Marshal.StructureToPtr(buffer, bufferPointer, true);

IntPtr o;
SocketError error = Unmanaged.WSA_Send(
    socket,
    bufferPointer,
    1,
    out o,
    SocketFlags.None,
    IntPtr.Zero,
    IntPtr.Zero);

And here is method declaration:

    [DllImport("Ws2_32.dll", SetLastError = true, EntryPoint = "WSASend")]
    public static extern SocketError WSA_Send(IntPtr socket, IntPtr buffer, int len, out IntPtr numberOfBytesSent, SocketFlags flags, IntPtr overlapped, IntPtr completionRoutine);

And this is my WSABUF declaration:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WsaBuf
{
    public ulong Len;

    public IntPtr Buf;

    public static WsaBuf Create(string str)
    {
        byte[] connectBuf = Encoding.ASCII.GetBytes(str);
        GCHandle pinnedArray = GCHandle.Alloc(connectBuf, GCHandleType.Pinned);
        return new WsaBuf { Buf = pinnedArray.AddrOfPinnedObject(), Len = (ulong)connectBuf.Length };
    }

    public void Free()
    {
        if (!Buf.Equals(IntPtr.Zero))
        {
            GCHandle.FromIntPtr(Buf).Free();
        }
    }
}

I receive nothing on other side. Any Idea?

Was it helpful?

Solution

u_long is unsigned long, which maps to uint because it is a 4 byte quantity on Microsoft Visual C compiler. Len should be uint. Probably, WSASend only looked at the first 4 bytes, found them to be 0 which is a zero length buffer.

Btw, you are misusing GCHandle.FromIntPtr. Look at the docs to see what it really does. It is immaterial to the question, so I won't elaborate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top