Wednesday, August 17, 2011

Introducing the connect(2) Function


In order to establish a connection with sockets, you call upon the connect(2) function. Its function synopsis is as follows:

#include <sys/types.h>
#include <sys/socket.h>
int connect (int sockfd, struct sockaddr *serv_addr, int addrlen);

This function takes three arguments. They are:
  1. The socket file descriptor sockfd that was returned by a former call to socket(2).
  2. The server address serv_addr that the program is connecting to.
  3. The length addrlen of the server address in bytes.

The server address and the server address length are the same socket address values that you would have supplied in a call to the sendto(2) function, if you were using UDP. The difference with connection-oriented protocols, however, is that you only establish the destination address once. After this function succeeds, all future communications will be with the socket addressed here. When the function call is successful, the return value is zero. Otherwise, -1 is returned to indicate that an error has occurred, and the nature of the error is recorded in the variable errno.

No comments:

Post a Comment