The listen function converts a data socket into a listening socket. In this manual, the term data socket means a socket that you can use to send and receive data, and the term listening socket means a socket that you can use to listen for attempts by other sockets to connect. When you first create a socket it is a data socket by default.
The system include file WinSock2.inc contains the following declaration for the listen function:
function listen(s : SOCKET; backlog : integer) : integer;
external dll='ws2_32.dll';
The first argument passed to the listen function is the data socket socket that you want to convert into a listening socket.
The second argument passed to the listen function is the maximum length of the queue of pending connections. If you pass a value, for this argument, that is too large then the underlying service provider will choose an appropriate value. If you are not sure what value you should use for this argument then use SOMAXCONN, which will cause the underlying service provider to choose an appropriate value. NOTE: The constant SOMAXCONN is declared in the system include file WinSock2.inc.
The listen 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. NOTE: The constant SOCKET_ERROR is declared in the system include file WinSock2.inc.
The following example function is taken from the sample sockets programs distributed with Irie Pascal, and demonstrates how to create a socket, bind it, and convert it into a listening socket.
//This function creates a listening socket.
//First it creates a socket. Then it binds the socket to
//a particular port (i.e. the port we want to listen on).
//The socket is not bound to any particular address (INADDR_ANY is used instead)
//because connections will be accepted from any IP address.
//Finally "listen" is called to convert the socket to a listing socket.
function CreateListeningSocket(port : integer) : socket;
var
s : socket;
sa : sockaddr_in;
iRet : integer;
begin (* CreateListeningSocket *)
s := createsocket(AF_INET, SOCK_STREAM, 0);
if s = INVALID_SOCKET then
FatalSocketError('CreateSocket call failed');
fill(sa, 0);
sa.sin_family := AF_INET;
sa.sin_port := htonl(port) shr 16;
sa.sin_addr := htonl(INADDR_ANY) shr 16;
iRet := bind(s, addr(sa), sizeof(sa));
if iRet <> 0 then
FatalSocketError('Call to bind failed');
iRet := listen(s, SOMAXCONN);
if iRet <> 0 then
FatalSocketError('Call to listen failed');
CreateListeningSocket := s;
end; (* CreateListeningSocket *)
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.