views:

807

answers:

4

I have a c++ win32 program that uses sockets to download some data from a server.

Before using sockets on Windows, WSAStartup must be called. MSDN says: "There must be a call to WSACleanup for each successful call to WSAStartup. Only the final WSACleanup function call performs the actual cleanup."

The easiest way for me is to call WSAStartup/WSACleanup each time I download a peace of data form the server. Most of the time there will be only one connection at a time, so that WSACleanup will perform an actual cleanup.

That is why I'm wondering, what the cost of WSAStartup and WSACleanup is? I means for performing an actual cleanup. If the calls to WSAStartup and WSACleanup only last a short time in comparison to the whole socket connection, then I can use the easy way. If not, I should take care to call WSACleanup only when exiting the program.

+4  A: 

WSAStartup() loads the dlls necessary. But if the dll is already loaded, WSAStartup() simply increases a counter. WSACleanup() decreases the counter and frees the dll once the counter reaches zero.

You should call WSAStartup() in the init function of your application, and WSACleanup() right before you exit your application.

Stefan
A: 

Just call WSAStartup once and never clean up. Seriously, this is kind of a piece of leftover architecture from Win3.1 and Win32s.

Joshua
A: 

Startup and exit calls are pretty straightforward. Why exactly is it easier to call the startup and cleanup functions around every call?

Andomar
+1  A: 

Use RAII to load them only once when the application starts and then to free them when you exit...

graham.reeds