I am trying to dynamically link winsock functions starting with WSASocket
, the following code compile just fine
#include <stdio.h>
#include <winsock2.h>
#include <windows.h>
typedef SOCKET (WINAPI * pWSASocket)(int, int, int, LPWSAPROTOCOL_INFOA, GROUP, DWORD);
int main()
{
HMODULE hmod = LoadLibrary("ws2_32.dll");
if (hmod == NULL)
{
printf("Failed to load ws2_32.dll\n");
exit(EXIT_FAILURE);
}
pWSASocket WSASocket = (pWSASocket)GetProcAddress(hmod, "WSASocket");
if (WSASocket == NULL)
{
printf("Failed to find function WSASocket\n");
exit(EXIT_FAILURE);
}
return 0;
}
but when running the binary I get the error
Failed to find function WSASocket
According the WINAPI docs WSASocket should be in Ws2_32.dll
but the GetProcAddress
returns a NULL
value
WSASocket
is a preprocessor symbol declared in WinSock2.h, not the name of an exported symbol. The symbols exported by ws2_32.dll are named WSASocketA
or WSASocketW
.
Since your function pointer declaration uses LPWSAPROTOCOL_INFOA
, you'll probably want to resolve WSASocketA
. If you were to use load-time dynamic linking instead, this would produce a deprecation warning.
If that is something you care about, link to the WSASocketW
symbol instead and use LPWSAPROTOCOL_INFOW
in the function pointer declaration.