next up previous
Next: Data Transfer Up: Introduction Previous: Binding local names

Connection Establishment

A connection is typically used for client-server interaction. A server advertizes a particular server at a well-known address and clients establish connections to that socket to avail of the offered service. Thus the connection estblishment procedure is asymmetric.

A server creates a socket, binds it to a ``well-known'' port number associated with the service, and then passively ``listens'' on the socket for requests to be served. It is possible for any unrelated process to rendezvous with the server. A client requests services from a server by initiating a ``connection'' to the server's socket. The client uses the connect system call to initiate a connection. For example, the following call establishes a connection to a socket whose address is specified using the variable ``sname''.

struct sockaddr_in sname;
int s;	/* socket descriptor returned by system call socket */

       sname.sin_family = AF_INET;
       sname.sin_port = PORTNUM; /* well-known port no */
       sname.sin_addr.s_addr = /* host address of the server */;

       connect(s, &sname, sizeof(sname));

For the server to receive a conection, it must perform two steps after binding its socket. The first is to indicate a willingness to listen for incoming connection requests:

    listen(fdTo,5);

The second parameter specifies the maximum number of outstanding connections that may be queued by the system when server is busy.

Once a socket is marked as listening, a server may accept a connection:

struct sockaddr_in from;
int fromlen;

       fromlen  = sizeof(from);
       newsock = accept(fdTo, &from,  &fromlen);

A new socket descriptor is returned on receipt of a connection. The identity of the client requesting connection is returned in the structure from and the length of that information is returned in fromlen. Figure 2 shows program for a remote login server that accepts requests for remote login from remote clients. Note that ``login'' is a well-known servicve and therefore has a well-known port number.

Once a connection is established, both client and server may exachnge data using several system calls.



Prasun Dewan
Mon Mar 27 11:27:55 EST 2000