If you want to make money online : Register now

Describe the Listen System Call

, , No Comments

 TCP server, binds to a well-known port and waits for a client to try to connect to it.

This process is called as “listening” and it is performed by calling the listen () system

The Listen system call is used in the server in the case of connection-oriented
communication to prepare a socket to accept messages from clients. It creates a
passive socket (recall the concept of passive and active mode of socket) from an
unconnected socket. ‘Listen’ initializes a queue for waiting connections. Before
calling listen, socket must be created and its address field must be set.

Usually Listen() is executed after both socket() and bind() calls and before accept()
[accept system call will be discussed in next sections].

int listen(int sockfd, int Max_conn)

On success, listen() returns “0”
On failure, it return
s “-1” and the error is in errno.

Listen takes two parameters, first the socket you would like to listen on and another is
the Maximum number of request that will be accepted on the socket at any given
time. Socket you would like to listen on is represented here as sockfd is the usual
socket file descriptor from the socket() system call. Maximum number of connections
allowed on the incoming queue at any given time is represented by backlog. On the
server all incoming connections requests from clients come and wait in one special
queue (from this queue server choose the connection and accept the request). We
have to define the limit on queue that how many connections can wait in a queue.
Generally this limit is set to 20. But you can set it with any other number also, for

listen (socket, 5), call will inform the operating system that server can only allow
five client sockets to connect at any one given time.

If the queue is full, then the new connection request will be rejected, which will result
in an error in the client application. Queued connections are removed from the queue
and completed with the accept() function, which also creates a new socket for
communicating with the client.

Example :

#define SERVERPORT 1729
int main()
int sockfd;
struct sockaddr_in ser_addr;
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
perror("socket error");


ser_addr.sin_family = AF_INET;
ser_addr.sin_port = htons(SERVERPORT);
ser_addr.sin_addr.s_addr = inet_addr(INADDR_ANY);
memset(&(ser_addr.sin_zero), '\0', 8); /* zero the rest of the struct */
if ( bind(sockfd, (struct sockaddr *)& ser_addr, sizeof(struct sockaddr)) < 0 )

if ( listen(sockfd, 5) < 0 ) / * Inform the operating sytem that server cn allow
only 5 clients*/
perror("listen error");

0 टिप्पणियाँ:

Post a Comment