Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is ConnectEx defined?

I want to use ConnectEx function on Windows7, with MSVC2010.

I am getting error C3861: 'ConnectEx': identifier not found

MSDN suggests the function should be declared in mswsock.h, however, when checking it, it's not defined there.

Any tips?

like image 412
Martin Sustrik Avatar asked Jun 10 '12 09:06

Martin Sustrik


1 Answers

If you read further into the MSDN article for ConnectEx() you mentioned, it says:

Note The function pointer for the ConnectEx function must be obtained at run time by making a call to the WSAIoctl function with the SIO_GET_EXTENSION_FUNCTION_POINTER opcode specified. The input buffer passed to the WSAIoctl function must contain WSAID_CONNECTEX, a globally unique identifier (GUID) whose value identifies the ConnectEx extension function. On success, the output returned by the WSAIoctl function contains a pointer to the ConnectEx function. The WSAID_CONNECTEX GUID is defined in the Mswsock.h header file.

Unlike other Windows API functions, ConnectEx() must be loaded at runtime, as the header file doesn't actually contain a function declaration for ConnectEx() (it does have a typedef for the function called LPFN_CONNECTEX) and the documentation doesn't specifically mention a specific library that you must link to in order for this to work (which is usually the case for other Windows API functions).

Here's an example of how one could get this to work (error-checking omitted for exposition):

#include <Winsock2.h> // Must be included before Mswsock.h
#include <Mswsock.h>

// Required if you haven't specified this library for the linker yet
#pragma comment(lib, "Ws2_32.lib")

/* ... */

SOCKET s = /* ... */;
DWORD numBytes = 0;
GUID guid = WSAID_CONNECTEX;
LPFN_CONNECTEX ConnectExPtr = NULL;
int success = ::WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER,
    (void*)&guid, sizeof(guid), (void*)&ConnectExPtr, sizeof(ConnectExPtr),
    &numBytes, NULL, NULL);
// Check WSAGetLastError()!

/* ... */

// Assuming the pointer isn't NULL, you can call it with the correct parameters.
ConnectExPtr(s, name, namelen, lpSendBuffer,
    dwSendDataLength, lpdwBytesSent, lpOverlapped);
like image 162
In silico Avatar answered Sep 19 '22 16:09

In silico