Cleaning up WinSock2

The WSACleanUp Function

Description

The WSACleanUp function is used to indicate that your program has finished using the WinSock2 library, and should be the last WinSock2 library function your program calls. Calling the WSACleanUp function allows the WinSock2 library to free any resources allocated on behalf of your program. Any sockets that are open when the WSACleanup function is called are reset and automatically deallocated as if the closesocket function was called. Calling the WSACleanup function may result in loss of data, if there are sockets that have been closed with the closesocket function but still have pending data to be sent, and the call to the WSACleanup function causes the WinSock2 library DLL to be unloaded from memory. In order to prevent loss of data, your program should call the shutdown function before calling the closesocket function and the WSACleanUp function.

There must be a call to the WSACleanUp function for every successful call to the WSAStartup function made by your program. Only the final call to the WSACleanUp function does the actual cleanup. The preceding calls simply decrement an internal reference count in the Ws2_32.dll.

Declaration

The system include file WinSock2.inc contains the following declaration for the WSACleanUp function:

function WSACleanup : integer;
  external dll='ws2_32.dll';

Arguments

None.

Return Values

The WSACleanUp function returns a value of integer type that indicates whether the call was successful. A value of zero means that the call succeeded. A value of SOCKET_ERROR indicates that the called failed, and in this case you can use the WSAGetLastError function to retrieve a code that identifies the error that caused the call to fail.

Sample Program

The sample program below illustrates how to call the WSAStartup and WSACleanUp functions.

(*$I winsock2.inc *)
program start(output);
var
 data : WSADATA;
 iRet : integer;
begin
 iRet := WSAStartUp($0202, data);
 if iRet <> 0 then
  begin
   writeln('WSAStartUp call failed. Return Code=', iRet);
   halt;
  end;
 writeln('WSAStartUp call succeeded.');
 writeln('Version: $', hex(data.wVersion));
 writeln('High Version: $', hex(data.wHighVersion));
 writeln('Description: ', data.szDescription);
 writeln('System Status: ', data.szSystemStatus);
 iRet := WSACleanUp
end.

Reference Information

The authoritative source of information about the WinSock2 library is the Microsoft Developers Network (MSDN). You can access the MSDN on the Microsoft website at msdn.microsoft.com.