Elmi Elmi -4 years ago 206
C# Question

Pinvoke / call native Windows API function from C#

from within my C#-application I use functions of an external DLL. This DLL itself uses network functions. So it is necessary to initialise Winsock out of my C#-application to let the network sockets work for this DLL. That's how I try to execute WSAStartup for initialisation, but it does not seem to work:

class Program
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct WSAData
{
internal Int16 version;
internal Int16 highVersion;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
internal String description;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
internal String systemStatus;

internal Int16 maxSockets;
internal Int16 maxUdpDg;
internal IntPtr vendorInfo;
}

[DllImport("ws2_32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern Int32 WSAStartup(Int16 wVersionRequested, out WSAData wsaData);

static void Main(string[] args)
{
WSAData wsaData;

wsaData.version = 0;
wsaData.highVersion = 0;
WSAStartup(0,out wsaData); // to initialise windows socket

... // calling external DLL functions
}
}


WSAStartup() seems to be called successfully but the used DLL is still not able to access network. So it seems WSAStartup() did not work for some reason. Any ideas what I'm doing wrong here?

Kind regards

Michael

Answer Source

You must pass 2 << 8 | 2 as the fist parameter (it is the version requested from the WSA)

Note that there is a small bug in the signature Microsoft produced (see Is the .NET use of WSAStartup safe for 64-bit apps?), but it isn't a problem, so you can ignore it.

You should always check the return values of the API functions you call:

int resp = WSAStartup(2 << 8 | 2, out wsaData); // to initialise windows socket

if (resp != 0)
{
    // Error
}

Technically the check suggested by Microsoft in https://msdn.microsoft.com/library/windows/desktop/ms742213.aspx is even more complex, because they do:

if (resp != 0 || wsaData.version != (2 << 8 | 2))
{
    // Error
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download