Interview Questions

Code Sample: Connection Establishment by Server - accept()

Beginners Guide to Sockets


(Continued from previous question...)

Code Sample: Connection Establishment by Server - accept()

#include &ltsys/types.h>
#include &ltsys/socket.h>

int accept(int sockfd, struct sockaddr *name,
      int *namelen)

The accept() call establishes a client-server connection on the server side. (The client requests the connection using the connect() system call.) The server must have created the socket using socket(), given the socket a name using bind(), and established a listen queue using listen().

sockfd is the socket file descriptor returned from the socket() system call. name is a pointer to a structure of type sockaddr as described above

struct sockaddr {
	u_short sa_family;
	char    sa_data[14];
};

Upon successful return from accept(), this structure will contain the protocol address of the client's socket. The data area pointed to by namelen should be initialized to the actual length of name. Upon successful return from accept, the data area pointed to by namelen will contain the actual length of the protocol address of the client's socket.

If successful, accept() creates a new socket of the same family, type, and protocol as sockfd. The file descriptor for this new socket is the return value of accept(). This new socket is used for all communications with the client.

If there is no client connection request waiting, accept() will block until a client request is queued.

accept() will fail mainly if sockfd is not a file descriptor for a socket or if the socket type is not SOCK_STREAM. In this case, accept() returns the value -1 and errno describes the problem.

(Continued on next question...)

Other Interview Questions