WSAStartup()
must be called before socket()
can be called, otherwise it will return a WSANOTINITIALISED
error.
You can call WSAStartup()
multiple times. It is preferred to call WSAStartup()
only once, but WinSock is reference counted so it can be called multiple times if needed. You must make sure that you call WSACleanup()
one time for each time that WSAStartup()
succeeds, or else the reference count will be unbalanced. For instance, you could call WSAStartup()
in your constructor and call WSACleanup()
in your destructor:
public class IPnetwork
{
private:
WSADATA wsaData ;
bool wsaInit;
...
public:
IPnetwork(char* serverIPaddress) ;
~IPnetwork() ;
} ;
.
IPnetwork::IPnetwork(char* serverIPaddress)
{
wsaInit = (WSAStartup(MAKEWORD(REQ_WINSOCK_VER,0), &wsaData) == 0);
...
}
IPnetwork::~IPnetwork()
{
if (wsaInit) WSACleanup();
}
bool IPnetwork::Connect()
{
if (!wsaInit)
return false ; /* winsock problem */
...
}
Though I would typically call them inside of a separate singleton class instead.