How to Connect System Call

, , No Comments

 Ans :

Generally “connect” function is used by client program to establish a connection to a
remote machine (server).

Syntax of connect is given below:

int connect(int sockfd, struct sockaddr_in *server_addr, int serv_addrlen);
connect() returns 0 if successful or returns -1 on unsuccessful and sets errno

In the connect call, sockfd is a socket file descriptor returned by socket(), server_addr
points to a structure with destination port and IP address and serv_addrlen set to
sizeof (struct sockaddr).

Initial code necessary for a TCP client:


#define SERVER_IP ""
#define SERVER_PORT 1729

int sockfd;
struct sockaddr_in ser_addr; /* will hold the destination addr */

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0))<0)

{ perror("socket error ");

Ser_addr.sin_family = AF_INET; /* inet address family */
Ser_addr.sin_port = htons(SERVER_PORT); /* destination port */
Ser_addr.sin_addr.s_addr = inet_addr(SERVER_IP); /* destination IP address */
memset(&(dest_addr.sin_zero), '\0', 8); /* zero the rest of the struct / *
/* In function void *memset(void *s, int c, size_t n); The memset() function
fills the first n bytes of the memory area pointed to be s with the constant byte c.*/

if (connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr))<0)
perror("connect error");

During the bind call example earlier we have ignored the local port number, now we
are concerned about the remote port. The kernel will choose a local port, and the site
we connect to, will automatically get this information from client.

If connectionless client (UDP) use the connect (), then the system call just stores the
server address specified by the process, so that the system knows where to send any
future data the process writes to the sockfd descriptor. Also, the socket will receive
only datagrams from this address. Note that the destination address is not necessary
for each Datagram sent, if we are connecting a UDP socket.

Connect system call result in actual connection establishment between the local and
remote system in case of connection-oriented protocol. At this point some agreement
for the future data exchange happens like buffer size, amount of data,
acknowledgement etc., as we have discussed earlier in Unit 3 of Block 1. This
exchange of information between client and server are known as 3-way handshake,

To use connect function, first of all client needs to call the socket (), then connect ()
function sets value of server socket address and client socket address is either
provided by bind system call or set by the operating system.

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

Post a Comment